安装流程
-
安装babel-preset-env和babel-loader
npm install --save-dev babel-preset-env babel-loader
-
根目录创建webpack.config.js并配置,内容参考如下:
module.exports = {
entry: './src/index.js',
output: {
path: __dirname,
filename: './build/bundle.js'
},
module: {
rules: [{
test: /\.js?$/,
exclude: /(node_modules)/,
loader: 'babel-loader'
}]
},
mode: 'development'
}
-
配置package.json中的scripts
"scripts": { "start": "webpack", "test": "echo \"Error: no test specified\" && exit 1" },
运行 npm start
有可能你会遇到报错
Error: Cannot find module '@babel/core' babel-loader@8 requires Babel 7.x (the package '@babel/core'). If you'd like to use Babel 6.x ('babel-core'), you should install 'babel-loader@7'.
说明你的babel依赖包不兼容,官方默认babel-loader | babel 对应的版本需要一致。有两种解决方法:
两种解决方案:
- 回退低版本:npm install -D babel-loader@7 babel-core babel-preset-env
- 更新到最高版本:npm install -D babel-loader @babel/core @babel/preset-env webpack
成功后你就可以在./build/bundle.js中看到转化完成的代码
使用示例
import util1 from './util1.js'
import { fn1, fn2 } from './util2.js'
console.log(util1)
fn1()
fn2()
export default { a: 100 }
export function fn1() {
alert('fn1')
}
export function fn2() {
alert('fn2')
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<p>test</p>
<script type="text/javascript" src="build/bundle.js"></script>
</body>
</html>
启动静态服务器 http-server -p 8881 (此为NodeJS本地服务器,在下载安装NodeJS的基础上,可通过 npm install http-server -g 安装)
即可在localhost:8881显示效果