【问题标题】:Import React from 'react' results in Uncaught SyntaxError: Unexpected identifier从 'react' 导入 React 导致 Uncaught SyntaxError: Unexpected identifier
【发布时间】:2018-07-03 00:26:28
【问题描述】:

我已经安装了 webpack 3 和 babel,我的条目 index.js/bundle.js 将构建并运行,我已经使用 ES7/8 功能对其进行了测试,但是导入不起作用并导致 Uncaught SyntaxError: Unexpected identifier。我尝试将 babel 配置放入我的应用程序根目录中的 package.json 以及单独的 .babelrc 文件中,但尝试导入时仍然出现错误。我是否缺少包或设置?

index.js(有效)

// does not work
// import React from 'react' 

// works
const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

console.log(Object.values(object1));

webpack.config.js

const path = require('path')

module.exports = {
  context: path.resolve(__dirname, 'app/assets/javascripts/source'),
  entry: './index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'app/assets/javascripts/webpack')
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      }
    ]
  }
}

.babelrc

{
  "presets": ["env", "react"]
}

package.json

}
  ...
  "license": "MIT",
  "scripts": {
    "build": "webpack",
  },
  "babel": {
    "presets": [
      "env",
      "react"
    ]
  },
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react": "^6.24.1",
    "prop-types": "^15.6.0",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "webpack": "^3.10.0",
    "webpack-dev-server": "^2.11.1"
  }
}

【问题讨论】:

  • 一边评论:reactreact-domprop-types 应该是 dependencies,而不是 devDependencies

标签: javascript npm webpack babeljs


【解决方案1】:

试试这个:transform-es2015-modules-amd,这个插件将 ES2015 模块转换为异步模块定义 (AMD)。

{
    presets: ["env", "react"],
    plugins: ["transform-es2015-modules-amd"]
 }

更多 transform-es2015-modules-amd

【讨论】:

    【解决方案2】:

    因为不翻译es6所以不工作,所以import语句不工作,你需要babel-preset-es2015

    并配置它.babelrc

    {
        "presets":[
            "es2015", "react"
        ]
    }
    

    【讨论】:

    • 我尝试了 es2015 预设,但仍然遇到同样的问题。但是我的 webpack 构建日志显示正在构建的模块。
    猜你喜欢
    • 2019-03-18
    • 2015-12-30
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-10
    • 2021-08-05
    相关资源
    最近更新 更多