//定义装饰器函数
function info(target){
target.info='Person.info'
}
//定义一个普通的类
@info
class Person{}
console.log(Person.info)
npm run dev
后的效果ERROR in ./src/index.js 31:0
Module parse failed: Unexpected character '@' (31: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
|
| //定义一个普通的类
> @info
| class Person{}
说明:@info是loader无法处理的高级JS语法,后面的babel-loader解决此问题
npm install -D babel-loader @babel/core @babel/plugin-proposal-decorators
安装完成后package.json添加依赖
"devDependencies": {
"@babel/core": "^7.19.6",
"babel-loader": "^9.0.0",
}
在webapck.config.js的module->rules数组中,添加loader规则如下
module: { //所有第三方文件模块的匹配规则
rules: [ //文件后缀名的匹配规则
{
test: /\.css$/, use: ['style-loader', 'css-loader']
},
{
test: /\.less$/, use: ["style-loader", "css-loader", "less-loader",],
},
{
test: /\.(png|jpg|gif)$/,use: [{loader: 'url-loader',options: {limit: 8192,}}],
},
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {loader: 'babel-loader',}
}
]
}
在项目根目录下,创建名为babel.config.js的配置文件,定义Babel的配置如下
module.exports = {
"plugins": [
["@babel/plugin-proposal-decorators", { legacy: true }],
]
}