我的项目中用到的 babel
是 6.26.3
版本;已有如下依赖
{
"babel-core": "^6.26.3",
"babel-helper-vue-jsx-merge-props": "^2.0.3",
"babel-loader": "^7.1.5",
"babel-plugin-syntax-jsx": "^6.18.0",
"babel-plugin-transform-runtime": "^6.22.0",
"babel-plugin-transform-vue-jsx": "^3.5.0",
"babel-preset-env": "^1.3.2",
"babel-preset-stage-2": "^6.22.0",
}
并且 webpack.base.conf.js
存在如下配置:(此处是vue-cli脚手架默认的配置)
module:{
rules:[
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
}
]
}
配置 .babelrc
即可
{
"presets": [
"stage-2"
]
}
在网上搜索了很多方法,此处仅列举以下几种方法:
babel-plugin-transform-object-rest-spread
和 babel-preset-es2015
依赖,并配置 .babelrc
此处仅列举个别.babelrc配置文案:
{
"presets": [
[
"env",
{
"modules": false,
"targets": {
"browsers": [
"> 1%",
"last 2 versions",
"not ie <= 8"
]
}
}
],
"stage-2",
[
"es2015",
{
"modules": false
}
]
],
"plugins": [
"transform-object-rest-spread"
]
}
这里虽然解决了上面的问题但是觉得太复杂了,于是接下来看第二种方法
.babelrc
{
"presets": [
["env", {
"modules": false
}],
"stage-2"
],
"plugins": ["transform-runtime", "transform-vue-jsx"]
}
此方法简单了很多,但是存在一个问题就是如果我引入的第三方库中存在扩展运算符,那么我们需要在
webpack.base.conf.js
中添加resolve('第三方库的路径')
module:{
rules:[
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client'), resolve('第三方库的路径')]
}
]
}
所以此配置如果用来解决第三方库问题是
不可行
,那么接下来看第三种方法
.babelrc
!!!
{
"presets": [
"stage-2"
]
}
解决第三方库问题需修改 webpack.base.conf.js
module:{
rules:[
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client'), resolve('第三方库的路径')]
}
]
}
此方法最简洁,并且无需再下载其他依赖,而且第三方库也可正常运行
个人博客
有空来坐坐https://www.wangyanan.online