我已经安装了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
:这是一个用于配置Babel转换器的文件,其中包含了各种插件和预设,以便将新的JavaScript语法转换为向后兼容的版本。{
"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"
}
}
react
,react-dom
和prop-types
应该是“dependencies”,而不是“devDependencies”。 - nem035