webpack-loader-使用babel-loader转换处理高级的js语法

发布时间 2023-05-28 18:11:45作者: Young_Yang_Yang

webpack只能打包处理一部分高级的JavaScript语法。对于那些webpack无法处理的高级js语法,需要借助于babel-loader进行打包处理。例如webpack无法处理下面的JavaScript代码:

//定义装饰器函数
function info(target) {
    target.info = 'Person info.'
}

//定义一个普通的类
@info
class Person {}

console.log(Person.info)

运行如下的命令安装对应的依赖包:
npm i babel-loader @babel/core @babel/plugin-proposal-decorators -D

在webpack.config.js的module->rules数组中,添加loader规则如下:

const path = require('path')
// 导入html插件,得到一个构造函数
const HtmlPlugin = require('html-webpack-plugin')
// 创建HTML插件的实例对象
const htmlPlugin = new HtmlPlugin({
    template: './src/index.html',//指定原文件的存放路径
    filename: './index.html'//指定生成的文件的存放路径
})
//使用Node.js中的导出语法,向外导出一个webpack的配置对象
module.exports = {
    // 代表webpack运行的模式,可选值有两个 development 和 production
    // 结论:开发时候一定要用development,因为追求的是打包的速度,而不是体积
    // 反过来,发布上线的时候一定能要用production,因为上线追求的是体积小,而不是打包速度快
    mode: 'production',
    plugins: [htmlPlugin],//通过plugins节点,使htmlPlugin插件生效
    entry: path.join(__dirname, './src/index.js'),//打包入口文件的路径
    output: {
        path: path.join(__dirname, './dist'),//输出文件的存放路径
        filename: 'bundle.js'//输出文件的名称
    },
    devServer: {
        open: true,
        port: 80,
        // contentBase: __dirname, -- 注意,这种写法已弃用
        static: {
            directory: path.join(__dirname, "/"),
        },
    },
    module: {
        rules: [
            //定义了不同模块对应的loader
            {test: /\.css$/, use: ['style-loader', 'css-loader']},
            //处理.less文件的loader
            {test: /\.less$/, use: ['style-loader', 'css-loader', 'less-loader']},
            //文件后缀名的匹配模块
            {test: /\.jpg|png|gif$/, use: 'url-loader'},
            //使用babel-loader处理高级的JS语法
            //在配置babel-loader的时候,程序员只需要把自己的代码进行转换即可,一定要排除node_module目录中的JS文件
            //因为第三方包中的JS兼容性,不需要程序员关心
            {test: /\.js$/, use: 'babel-loader', exclude: /node_modules/}
        ]
    }
}

在项目根目录下,创建名为babel.config.js的配置文件,定义Babel的配置项如下:

module.exports = {
    //声明babel可用的插件
    //将来,webpack在调用babel-loader的时候,会先加载plugins插件来使用
    plugins: [['@babel/plugin-proposal-decorators', {legacy: true}]]
}

详情请参考Babel的官网https://babeljs.io/docs/en/babel-plugin-proposal-decorators