首页 > 解决方案 > Webpack 4 和 Babel 7 "import" Uncaught SyntaxError: Unexpected identifier in React

问题描述

我一直在尝试设置 Webpack 4 和 Babel 7 以在 React 中使用 ES6“导入”。我在“从'react'导入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')
        }),
    ]}

标签: reactjswebpackecmascript-6babeljs

解决方案


好的,在吐出我的 webpack 配置后,我似乎已经解决了问题。问题是由此引起的:

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

我会看看我是否能找到导致 Webpack 不与此捆绑的确切原因。无论如何感谢所有的帮助!


推荐阅读