Webpack 4和Babel 7“导入”未捕获的SyntaxError:React中意外的标识符

时间:2018-11-20 14:14:42

标签: reactjs webpack ecmascript-6 babel

我一直在尝试将Webpack 4和Babel 7设置为与React中的ES6“导入”一起使用。我在“从'反应'导入React“时不断收到” Uncaught SyntaxError:Unexpected identifier“;在Chrome 71中使用。它可以在Webpack 3和Babel 6中使用,所以我认为Babel设置有问题。

这些是我的开发依赖项:

"@babel/core": "^7.1.6",
"@babel/plugin-proposal-class-properties": "^7.1.0",
"@babel/plugin-proposal-decorators": "^7.1.6",
"@babel/plugin-syntax-dynamic-import": "^7.0.0",
"@babel/preset-env": "^7.1.6",
"@babel/preset-react": "^7.0.0",
"@babel/register": "^7.0.0",
"babel-loader": "^8.0.4",
"webpack": "^4.26.0",
"webpack-dev-server": "^3.1.10"

我的.babelrc看起来像这样:

{
"presets": ["@babel/preset-env", "@babel/preset-react"],
"plugins": [
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    ["@babel/plugin-proposal-class-properties", { "loose": true }],
    ["@babel/syntax-dynamic-import"]
]
}

我也一直在尝试babel.config.js,但这并不占优势。

我的webpack-config.js文件:

const HTMLWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const webpack = require('webpack');

const HTMLWebpackPluginConfig = new HTMLWebpackPlugin({
    template: __dirname + '/src/index.html',
    filename: 'index.html',
    injext: 'body'
})

module.exports = {
    entry: ["babel-polyfill", __dirname + '/src/index.js'],
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader'
                }
            },
            {
                test: /\.scss$/,
                loader: ExtractTextPlugin.extract('css-loader!sass-loader')
            },
        ]
    },

    output: {
        filename: 'transformed.js',
        path: __dirname + 'build'
    },
    devServer: {
      contentBase: './src/',
      historyApiFallback: true,
      hot: true,
      port: 8000,
      publicPath: "/src/public",
      noInfo: false
    },
    plugins: [
        HTMLWebpackPluginConfig,
        new ExtractTextPlugin('public/css/style.css', {
            allChunks: true
        }),

        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'production')
        }),
    ]}

1 个答案:

答案 0 :(得分:0)

好吧,在通过我的webpack配置吐痰之后,我似乎已经解决了问题。问题是由以下原因引起的:

devServer: {
  contentBase: './src/',
  historyApiFallback: true,
  hot: true,
  port: 8000,
  publicPath: "/src/public",
  noInfo: false
},

我将看看我是否能找到导致Webpack不捆绑的确切原因。仍然感谢您的所有帮助!