写过 替换字符串 中指定文本的loader 和 删除项目中的 console.log() 打印语句。
思路:
- 在 src 目录下面 新建一个 loaders 目录
- 编写项目需要的 loader
- 比如编写一个 移除 console.log() 的loader
- 新建一个 removeConsoleLog.js 文件
- module.exports 导出一个函数,这个函数接受一个参数,source,源文件字符串
- 在函数中对这个字符串 使用 replace + 正则 把console.log 替换为 空文本
- 返回处理后的字符串
- loader 也可以接受参数,可以借助于 loader-utils 工具获取参数,也可以使用 this.query 获取
- module.export 对外暴露的函数,不能使用箭头函数,因为 loader 中的 this 是有上下文的
使用 自定义 loader
- 在 webpack.config.js 中使用
- 使用 use 指定 loader 的时候,需要写上完整路径,否则找不到
- 因为 webpack 在查找loader 的时候,先从 node_modules 目录查找
- 如果不想写 完整路径,需要在 resolveLoader 配置项中配置 modules 选项,指定 loader 目录
// 替换字符串 loadermodule.exports = function(source) {console.log(this.query.params + '接受参数');const handleContent = source.replace('框架', 'Vue框架').replace('JS', 'JavaScript')return handleContent}// 移除 console.log loadermodule.exports = function removeConsoleLog(source) {const handleContent = source.replace(/console\.log\(\S*\)/g, '')return handleContent}// webpack.config.jsresolveLoader: {modules: ['node_modules', './src/loaders']},module: {rules: [{test: /\.js$/,use: [{loader: 'removeConsoleLog'},{loader: './src/loaders/replaceLoader.js',options: {params: 'test replace string...'}}]}]}
