从'react'导入React导致Uncaught SyntaxError:意外的标识符 [英] Import React from 'react' results in Uncaught SyntaxError: Unexpected identifier
问题描述
我已经与babel一起安装了webpack 3,并且我的条目index.js/bundle.js
将生成并运行,我已经使用ES7/8功能对其进行了测试,但是导入无法正常工作,并导致Uncaught SyntaxError: Unexpected identifier
.我尝试将babel配置放在应用程序根目录中的package.json
以及单独的.babelrc
文件中,但是在尝试导入时仍然出现错误.我是否缺少包裹或设置?
I've installed webpack 3 along with babel and my entry index.js/bundle.js
will build and run, which I've tested with ES7/8 features, however imports won't work and result in Uncaught SyntaxError: Unexpected identifier
. I've tried putting the babel config in the package.json
as well as in a separate .babelrc
file in my app root directory but I still get the error when trying to import. Am I missing a package or setting?
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"
}
}
推荐答案
尝试一下:transform-es2015-modules-amd,此插件将ES2015模块转换为异步模块定义(AMD).
Try this : transform-es2015-modules-amd , This plugin transforms ES2015 modules to Asynchronous Module Definition (AMD).
{
presets: ["env", "react"],
plugins: ["transform-es2015-modules-amd"]
}
更多 transform-es2015-modules-amd
这篇关于从'react'导入React导致Uncaught SyntaxError:意外的标识符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!