Webpack 4 - Module parse failed: Unexpected character '@'

前端 未结 2 899
甜味超标
甜味超标 2021-01-17 14:03

I recently upgraded from Webpack 3 to 4. It\'s now throwing an error:

Module parse failed: Unexpected character \'@\' You may need an appropriate lo

相关标签:
2条回答
  • 2021-01-17 14:26

    The problem was the script I was using to run Webpack did not specify the config file. This is what it should look like:

    "scripts": {
      "watch": "./node_modules/.bin/webpack --watch --config webpack.dev.js",
    },
    

    I believe this was generating the @import problem because it was not loading the css-loader as without specifying the config file like above, it uses a default Webpack development config which does not include the css-loader.

    0 讨论(0)
  • 2021-01-17 14:45

    As I mentioned in a comment on your question there's an open issue with Webpack 4 compatibility: https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/701

    A fix for now is to install the alpha version of the library. I've done a small setup just now to test this and it works with webpack 4.

    Install the alpha version npm i -D extract-text-webpack-plugin@next --save. Then install css-loader, sass-loader and node-sass.

    Then in the webpack config file:

    const ExtractTextPlugin = require('extract-text-webpack-plugin');
    
    ...
    
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                use: {
                    loader: 'babel-loader'
                },
                exclude: /node_modules/,
                include: path.join(__dirname, 'src')
            },
            {
                test: /\.scss$/,
                loader: ExtractTextPlugin.extract(['css-loader', 'sass-loader'])
            }
        ]
    },
    
    plugins: [
        new ExtractTextPlugin('bundle.css'),
    ]
    

    This correctly worked for me, and also concatenated multiple scss files that were using @import statements.

    In package.json it should look like

    "extract-text-webpack-plugin": "^4.0.0-beta.0",
    "webpack": "^4.8.3"
    

    Edit: Just as a side note, apparently mini-css-extract-plugin works fine with webpack 4.

    0 讨论(0)
提交回复
热议问题