webpack-loader

·  阅读 81

初始化

创建项目

mkdir webpack-loader
npm init -y
复制代码

webpack.config.js

const path = require('path')

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  mode: 'development',
  module: {
    rules: [
      {
        test: /\.js$/,
        use: {
          loader: 'var-to-const-loader'
        }
      }
    ]
  },
  resolveLoader: {
    modules: [
      path.resolve(__dirname, 'node_modules'),
      path.resolve(__dirname, 'loaders')
    ]
  }
}

复制代码

匹配替换loader

var替换成const

同步

// loaders/var-to-const-loader.js

function loader (source) {
  return source.replace(/var/g, 'const')
}
module.exports = loader
复制代码

异步

// loaders/var-to-const-loader.js

function loader (source) {
  const callback = this.async()
  setTimeout(() => {
    callback(null, `${source.replace(/var/g, 'const')}`)
  }, 3000)
}
module.exports = loader
复制代码
分类:
前端
标签:
分类:
前端
标签: