Unexpected token when trying to load css with webpack and babel

13,665

Solution 1

I had to remove from:

{
  test: /\.css$/,
  use: [
         { loader: 'style-loader' },
         { loader: 'css-loader' }
       ],
       include: [
                    path.resolve(__dirname, "src","client")
       ],
}

to:

 {
      test: /\.css$/,
      use: [
             { loader: 'style-loader' },
             { loader: 'css-loader' }
           ],
    }

This one works in my case. I don´t know why.

Solution 2

To create npm package, you can build like to:

module: {
    rules: [
      {
        test: /\.js$/,
        include: path.resolve(__dirname, 'src'),
        exclude: /(node_modules|bower_components|build)/,
        loader: 'babel-loader'
      },
      {
        test: /\.(css|less)$/,
        use: ["style-loader", "css-loader"]
      }
    ]
  },

Solution 3

If you want to use simple css:

import './text.css';

But if you want to use CSS Modules, I assume that according to added CSS in your import, check https://github.com/css-modules/css-modules.

Also, try to change webpack config:

{
    test: /\.css$/,
    loader: 'style-loader!css-loader!',
  },

Check example:

Solution 4

Since you are rendering your React components which depend on the webpack CSS loader in the backend, on your Express server, you need to run your server-side code through webpack, just as you do your client-side code.

In the project I'm currently working on, I have two webpack builds, each with their own config. One produces a bundle named server.js, the other client.js. In production, I start the server by running node server.js. For local dev, I use a script that rebuilds my server.js when changes in the backend are detected.

It looks like this (file name backend-dev.js):

const path = require('path');
const webpack = require('webpack');
const spawn = require('child_process').spawn;

const compiler = webpack({
    // add your webpack configuration here
});
const watchConfig = {
    // compiler watch configuration
    // see https://webpack.js.org/configuration/watch/
    aggregateTimeout: 300,
    poll: 1000
};

let serverControl;

compiler.watch(watchConfig, (err, stats) => {
    if (err) {
        console.error(err.stack || err);
        if (err.details) {
            console.error(err.details);
        }
        return;
    }

    const info = stats.toJson();

    if (stats.hasErrors()) {
        info.errors.forEach(message => console.log(message));
        return;
    }

    if (stats.hasWarnings()) {
        info.warnings.forEach(message => console.log(message));
    }

    if (serverControl) {
        serverControl.kill();
    }

    // change server.js to the relative path to the bundle created by webpack, if necessary
    serverControl = spawn('node', [path.resolve(__dirname, 'server.js')]);

    serverControl.stdout.on('data', data => console.log(data.toString()));
    serverControl.stderr.on('data', data => console.error(data.toString()));
});

You can start this script on the command line with

node backend-dev.js

When you make changes in your server code, webpack will recompile and restart your server.

Note that I have omitted the actual webpack configuration from the above example, because your mileage will vary. You insert it at the beginning, see code comment.

Share:
13,665
Mike
Author by

Mike

Updated on June 12, 2022

Comments

  • Mike
    Mike almost 2 years

    I am building a react app using Express, I tries to add a style loader/css loader to enable importing css, but when i start my server i get the following error:

    M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox>npm run start:dev
    
    > [email protected] start:dev M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox
    > cross-env NODE_ENV=development && npm run build:dev && nodemon --exec babel-node -- src/server/server.js
    
    
    > [email protected] build:dev M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox
    > webpack -d
    
    Hash: 1b4953ee761d210e2488
    Version: webpack 2.2.1
    Time: 2567ms
        Asset     Size  Chunks                    Chunk Names
    bundle.js  2.54 MB       0  [emitted]  [big]  js
       [6] ./~/react/react.js 55 bytes {0} [built]
      [23] ./~/react/lib/React.js 2.71 kB {0} [built]
      [24] ./~/react-router-dom/es/index.js 2.21 kB {0} [built]
      [89] ./~/react-router-dom/es/Link.js 4.67 kB {0} [built]
      [94] ./~/react-dom/index.js 58 bytes {0} [built]
     [195] ./~/react-router-dom/es/MemoryRouter.js 259 bytes {0} [built]
     [196] ./~/react-router-dom/es/NavLink.js 3.36 kB {0} [built]
     [197] ./~/react-router-dom/es/Prompt.js 253 bytes {0} [built]
     [198] ./~/react-router-dom/es/Redirect.js 255 bytes {0} [built]
     [199] ./~/react-router-dom/es/Route.js 252 bytes {0} [built]
     [201] ./~/react-router-dom/es/StaticRouter.js 259 bytes {0} [built]
     [202] ./~/react-router-dom/es/Switch.js 253 bytes {0} [built]
     [203] ./~/react-router-dom/es/matchPath.js 256 bytes {0} [built]
     [204] ./~/react-router-dom/es/withRouter.js 257 bytes {0} [built]
     [236] ./src/client/app-client.js 706 bytes {0} [built]
        + 222 hidden modules
    [nodemon] 1.11.0
    [nodemon] to restart at any time, enter `rs`
    [nodemon] watching: *.*
    [nodemon] starting `babel-node src/server/server.js`
    M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babel-core\lib\transformation\file\index.js:590
          throw err;
          ^
    
    SyntaxError: M:/MainFiles/MyStuff/Code/react/FlexBoardToolBox/src/client/components/Test/text.css: Unexpected token (1:0)
    ←[0m←[31m←[1m>←[22m←[39m←[90m 1 | ←[39m←[33m.←[39mtest{
     ←[90m   | ←[39m←[31m←[1m^←[22m←[39m
     ←[90m 2 | ←[39m    background←[33m:←[39m blue←[33m;←[39m
     ←[90m 3 | ←[39m    font←[33m-←[39msize←[33m:←[39m ←[35m1.234←[39mpx←[33m;←[39m
     ←[90m 4 | ←[39m} ←[0m
        at Parser.pp$5.raise (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:4373:13)
        at Parser.pp.unexpected (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:1716:8)
        at Parser.pp$3.parseExprAtom (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:3683:12)
        at Parser.parseExprAtom (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:7016:22)
        at Parser.pp$3.parseExprSubscripts (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:3427:19)
        at Parser.pp$3.parseMaybeUnary (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:3407:19)
        at Parser.pp$3.parseExprOps (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:3337:19)
        at Parser.pp$3.parseMaybeConditional (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:3314:19)
        at Parser.pp$3.parseMaybeAssign (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:3277:19)
        at Parser.parseMaybeAssign (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:6242:20)
    [nodemon] app crashed - waiting for file changes before starting...
    

    my package.json file:

    {
      "name": "flex_board_tools",
      "version": "1.0.0",
      "description": "tool box",
      "main": "server.js",
      "scripts": {
        "start": "npm run build && babel-node src/server/server.js",
        "start:dev": "cross-env NODE_ENV=development && npm run build:dev && nodemon --exec babel-node -- src/server/server.js",
        "start:universal": "cross-env UNIVERSAL=true && npm run start",
        "start:dev:universal": "cross-env NODE_ENV=development && cross-env UNIVERSAL=true && npm run start:dev",
        "build": "cross-env NODE_ENV=production webpack -p",
        "build:dev": "webpack -d",
        "build:dev:watch": "webpack -d --watch"
      },
      "author": "Bender",
      "license": "MIT",
      "dependencies": {
        "babel-cli": "^6.18.0",
        "babel-core": "^6.18.2",
        "babel-preset-es2015": "^6.18.0",
        "babel-preset-react": "^6.16.0",
        "babel-preset-stage-2": "^6.24.1",
        "ejs": "^2.5.2",
        "express": "5.0.0-alpha.5",
        "react": "15.4.2",
        "react-addons-css-transition-group": "^15.4.0",
        "react-dom": "15.4.2",
        "react-router-dom": "^4.0.0",
        "react-toolbox": "^2.0.0-beta.8"
      },
      "devDependencies": {
        "babel-loader": "^6.4.1",
        "babel-register": "^6.18.0",
        "cross-env": "^4.0.0",
        "css-loader": "^0.28.0",
        "eslint": "^3.18.0",
        "eslint-config-airbnb": "^14.1.0",
        "eslint-plugin-import": "^2.2.0",
        "eslint-plugin-jsx-a11y": "^4.0.0",
        "eslint-plugin-react": "^6.10.3",
        "extract-text-webpack-plugin": "^2.1.0",
        "isomorphic-style-loader": "^2.0.0",
        "nodemon": "^1.11.0",
        "style-loader": "^0.16.1",
        "webpack": "2.2.1"
      }
    }
    

    my webpack.config.babel.js

    import path from 'path';
    const ExtractTextPlugin = require("extract-text-webpack-plugin");
    
    console.log("DIR: " + __dirname);
    const config = {
        entry: {
            js: './src/client/app-client.js',
        },
        output: {
            path: path.join(__dirname, 'src', 'client', 'static', 'js'),
            filename: 'bundle.js',
        },
        module: {
            rules: [
                {
                    test: [/\.jsx$/, /\.js$/], //path.join(__dirname, 'src'),
                    exclude: ["bower_components", "node_modules"],
                    use: {
                        loader: 'babel-loader',
                        options: 'cacheDirectory=.babel_cache',
                    },
                },
    
                {
                    test: /\.css$/,
                    use: [
                        { loader: 'style-loader' },
                        { loader: 'css-loader' }
                    ],
                    include: [
                        path.resolve(__dirname, "src","client")
                    ],
                }
    
            ]
    
    
    
        },
        plugins: [
    
        ]
        ,
    
    };
    
    export default config;
    

    sample usage (also tried import "./text.css"):

    import React from 'react';   
    import css from './text.css';
    
    
    export class Test1 extends React.Component {
    
    
     render() {
        return (<div className="test">
          Test1 File
    
        </div>
        );
      }
    }
    
    export default Test1;
    

    text.css

    .test{ 
        background: blue;
        font-size: 1.234px; 
    }
    

    Ive been at it for hours, cannot seem to find what is wrong.