ada*_*ng3 7 javascript babel npm webpack babeljs
我已经与babel一起安装了webpack 3,并且我的条目index.js/bundle.js将构建并运行,我已经使用ES7 / 8功能对其进行了测试,但是导入无法正常工作,并导致Uncaught SyntaxError: Unexpected identifier。我尝试将babel config放在应用程序根目录的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));
Run Code Online (Sandbox Code Playgroud)
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']
}
}
}
]
}
}
Run Code Online (Sandbox Code Playgroud)
.babelrc
{
"presets": ["env", "react"]
}
Run Code Online (Sandbox Code Playgroud)
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"
}
}
Run Code Online (Sandbox Code Playgroud)
试试这个:transform-es2015-modules-amd,这个插件将 ES2015 模块转换为异步模块定义(AMD)。
{
presets: ["env", "react"],
plugins: ["transform-es2015-modules-amd"]
}
Run Code Online (Sandbox Code Playgroud)
更多信息请参见 transform-es2015-modules-amd