第一步:通过npm下载安装必要的依赖包
# 第一套包,相当于babel的转换工具
npm i babel-core babel-loader babel-plugin-transform-runtime -D
# 第二套包,babel的语法
npm i babel-preset-env babel-preset-stage-0 -D
安装第一个包出现警告:
npm WARN babel-loader@8.0.6 requires a peer of @babel/core@^7.0.0 but none is installed. You must install peer dependencies yourself.
意思是没有安装7.0.0版本的babel-loader,解决办法就是卸载当前版本,再重新安装7.0.0版本。
#卸载新版
npm uninstall babel-loader -D
#再安装7.0.0版
npm i babel-loader@7.0.0 -D
第二步:配置webpack.config.js
在module选项中添加新的rule,表示用babel解释.js文件,但node_modules文件夹除外,否则会导致错误:
{ test: /\.js$/, use: ['babel-loader'], exclude: /node_modules/ }
第三步:在项目根目录中新建.babelrc配置文件
配置文件内容(文件遵循JSON标准,比如不允许使用注释、必须使用双引号等):
{
"presets": ["env", "stage-0"],
"plugins": ["transform-runtime"]
}