webpack-自定义babel-loader

55 阅读1分钟

自定义验证规则

自定义json文件

{
    "type": "object",
    "properties": {
        "persets": {
            "type": "array"
        }
    },
    "additionalProperties": true
}

引入依赖

@babel/preset-env @babel/core 写入自定义文件

const schema = require("./index.json")
const babel = require("@babel/core")
module.exports = function (content, sourcemap, meta) {
const options = this.getOptions(schema) // 检验是否符合自定义规则
const callback = this.async()  // 异步处理loader
babel.transform(content, options, function (err, result) {
   // result; // => { code, map, ast }
   if (err) {
       callback(err); // 返回错误失败值
   } else { 
       callback(null, result.code); // 返回成功值
   }
})
}

在webpack.config.js文件引入

 {
        test: /\.js$/g,
        loader: './loader/babel-loader/index.js', // 路径根据你的项目自己引入
        options: {
          // 引入配置规则
          "presets": ["@babel/preset-env"]
        }
      }