vue2:p23 webpack处理高级js语法 babel-loader
webpack 只能打包处理一部分高级的 JavaScript 语法。对于那些 webpack 无法处理的高级 js 语法,需要借助于 babel-loader 进行打包处理
1.安装
npm i babel-loader @babel/core @babel/plugin-proposal-decorators -D
npm i babel-loader@8.2.2 @babel/core@7.14.6 @babel/plugin-proposal-decorators@7.14.5 -D
2.配置webpack.config.js
const path=require('path');
const HtmlPlugin=require('html-webpack-plugin')
const htmlPlugin=new HtmlPlugin({
template:'./src/index.html',
filename:'./index.html'
})
module.exports={
mode:'development',
entry:path.join(__dirname,'./src/index.js'),
output:{
path:path.join(__dirname,'./dist/'),
filename:'main.js'
},
plugins:[htmlPlugin],
devServer:{
open:true,
port:5000,
host:'127.0.0.1'
},
module:{
rules:[
{test:/\.css$/,use:['style-loader','css-loader']},
{test:/\.less$/,use:['style-loader','css-loader','less-loader']},
//单位byte,小于10240字节图片转为base64格式
{test:/\.jpg|png|gif$/,use:'url-loader?limit=10000'},
//【1】排除依赖目录下相关js,防止处理其它非目标js
{test:/\.js$/,use:'babel-loader',exclude:'/node_modules/'}
]
}
}
3.根目录新建配置babel.config.js
module.exports={
// 声明 babel 可用的插件
// 将来,webpack 在调用 babel-loader 的时候,会先加载 plugins 插件来使用
plugins: [['@babel/plugin-proposal-decorators', { legacy: true }]]
}
4.src/index.js写装饰器高级语法
// 定义装饰器函数
function info(target) {
target.info = 'Person info.'
}
// 定义一个普通的类
@info
class Person {}
console.log(Person.info)
5.重新运行npm run dev
控制台输出:Person info
6。不配置babel会进行如下报错
ERROR in ./src/index.js 19:0
Module parse failed: Unexpected character '@' (19:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders