Skip to content

手写 loader

javascript
npm i -D @babel/parser @babel/traverse @babel/generator @babel/types
  • @babel/parser 将源代码解析成 Ast
  • @babel/traverse 对 ast 节点进行递归遍历,生成一个便于操作、转换的 path 对象
  • @babel/generator 将 ast 解码生成 js 代码
  • @babel/types 通过该模块对具体 ast 节点进行增、删、改、查

javascript
const parser = require('@babel/parser')
const traverse = require('@babel/traverse').default
const generator = require('@babel/generator').default
const t = require('@babel/types')
module.exports = function (source) {
  const ast = parser.parse(source, { sourceType: 'module' })
  traverse(ast, {
    CallExpression(path) {
      if (
        t.isMemberExpression(path.node.callee) &&
        t.isIdentifier(path.node.callee.object, { name: 'console' })
      ) {
        path.remove()
      }
    }
  })
  const output = generator(ast, {}, source)
  return output.code
}

使用

javascript
const path = require('path')
module.exports = {
  mode: 'development',
  entry: path.resolve(__dirname, 'index.js'),
  output: {
    filename: '[name].[contenthash].js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        use: path.resolve(__dirname, 'drop-console.js')
      }
    ]
  }
}

如有转载或 CV 的请标注本站原文地址