1、安装依赖
npm install babel-polyfill
npm install --save-dev @babel/core @babel/plugin-transform-runtime @babel/preset-env es6-promise @babel/polyfill babel-plugin-transform-remove-console
2、main.js中引用babel-polyfill、es6-promise
// 解决低版本兼容性问题
import 'babel-polyfill';
import Es6Promise from 'es6-promise';
require('es6-promise').polyfill();
Es6Promise.polyfill();
针对vue-cli2项目
3、创建一个.babelrc文件
{
"presets": [
"es2015" ,
"stage-2"
],
"plugins": [
"transform-vue-jsx",
"transform-runtime",
["import", [{ "libraryName": "vant", "style": true }]]
],
}
或者
{
"presets": ["@babel/preset-env"],
"plugins": [
"@babel/plugin-transform-runtime"
]
}
4、webpack.base.conf.js
const path = require('path')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
context: path.resolve(__dirname, '../'),
entry: {
app: ["babel-polyfill", "./src/main.js"]
// app: './src/main.js'
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
// include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
query: {
presets: ['es2015']
},
include: [
resolve('src'),
resolve('static/js'),
resolve('test'),
resolve('node_modules/webpack-dev-server/client'),
resolve('node_modules/vant')
]
},
]
}
}
针对vue-cli3项目
3、新建一个babel的配置文件 babel.config.js
这里的 transform-remove-console 用来在打包之前删除控制台打印,不需要的可以去掉
var plugins = [];
if (['production', 'prod'].includes(process.env.NODE_ENV)) {
plugins.push("transform-remove-console")
}
module.exports = {
presets: [
[
"@vue/app",
{
"useBuiltIns": "entry",
polyfills: [
'es6.promise',
'es6.symbol'
]
}
]
],
plugins: plugins
}
4、vue.config.js
const path = require('path');
function resolve(dir) {
return path.join(__dirname, '.', dir);
}
module.exports = {
... // 其他配置
publicPath: process.env.NODE_ENV === "production" ? "./" : "./",
// 默认情况下 babel-loader 会忽略所有 node_modules 中的文件。
// 如果你想要通过 Babel 显式转译一个依赖,可以在这个选项中列出来
transpileDependencies: [],
chainWebpack: config => {
config.module.rule('compile')
.test(/\.js$/)
.include
.add(resolve('src'))
.add(resolve('test'))
.add(resolve('node_modules/webpack-dev-server/client'))
.add(resolve('node_modules'))
.end()
.use('babel')
.loader('babel-loader')
.options({
presets: [
['@babel/preset-env', {
modules: false
}]
]
});
}
}
转载于:https://blog.csdn.net/Maggie_01/article/details/101159448