从'react'导入React会导致Uncaught SyntaxError:意外的标识符

时间:2018-01-24 03:26:06

标签: javascript npm webpack babeljs babel

我已经安装了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"
  }
}

2 个答案:

答案 0 :(得分:3)

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

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

更多 transform-es2015-modules-amd

答案 1 :(得分:1)

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

并配置 .babelrc

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