以下是一个自定义loader replace-loader
,实现一个类似模板引擎变量替换的简单功能
文件目录
.
├── dist
│ └── index.js # 打包结果
├── loaders
│ └── replace-loader.js # 自定义loader
├── src
│ └── index.js # 要打包的文件入口
├── package.json # 依赖配置
└── webpack.config.js # 打包配置
package.json
{
"name": "loader-demo",
"version": "1.0.0",
"description": "a webpack loader demo",
"scripts": {
"build": "webpack"
},
"devDependencies": {
"loader-utils": "^2.0.0",
"webpack": "^5.47.0",
"webpack-cli": "^4.7.2"
}
}
webpack.config.js
'use strict';
const path = require('path');
module.exports = {
// 打包入口
entry: {
index: './src/index.js',
},
// 指定输出地址及打包出来的文件名
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].js',
},
// Loader路径
resolveLoader: {
modules: ['node_modules', './loaders'],
},
module: {
rules: [
{
test: /.js$/,
use: {
loader: 'replace-loader',
// 传递参数
options: {
name: 'Tom',
},
},
},
],
},
// 开发环境
mode: 'production',
};
loaders/replace-loader.js
const loaderUtils = require('loader-utils');
module.exports = function (source) {
// 获取参数
let options = loaderUtils.getOptions(this);
for (let [key, value] of Object.entries(options)) {
source = source.replace(`{{${key}}}`, value);
}
return source;
};
src/index.js
console.log('hi {{name}}');
指定打包命令
$ npm run build
dist/index.js
console.log("hi Tom");