一、初始化一个项目
1、npm 初始化
npm init -y
2、安装需要的依赖
package.json文件:{"name": "webpack-plugin-test","version": "1.0.0","description": "","main": "main.js","scripts": {"build": "webpack","dev": "webpack-dev-server"},"keywords": [],"author": "","license": "ISC","devDependencies": {"@babel/core": "^7.18.6","babel-loader": "^8.2.5","html-webpack-plugin": "^5.5.0","webpack": "^5.73.0","webpack-cli": "^4.10.0","webpack-dev-server": "^4.9.3"}
}
3、新建文件tpl-loader,info.tpl,主入口文件main.js,webpack配置文件 webpack.config.js
二、编写info.tpl和主入口文件main.js文件,配置webpack
// info.tpl文件:<div><h1>{{ name }}</h1><div>{{ age }}</div><div>{{ sex }}</div>
</div>// main.js文件:import tpl from './info.tpl';const appDom = document.getElementById('app');appDom.innerHTML = tpl({name: '张三',age: 19,sex: '男'
})// webpack.config.js文件:const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');module.exports = {mode:'development',devtool: 'eval-cheap-module-source-map',// 一般开发环境配置// development devtool: 'eval-cheap-module-source-map',// 一般情况生产环境配置// production devtool: 'cheap-module-source-map',entry:'./src/main.js',output:{filename: 'bundle.js',path:resolve(__dirname,'./dist')},resolveLoader: {modules: [ 'node_modules',resolve(__dirname,'loaders')]},module: {rules: [{test: /\.tpl$/,use: ['babel-loader',{loader: 'tpl-loader',options: {log: true}}]}]},plugins: [new HtmlWebpackPlugin({template:'./public/index.html',filename: 'index.html',minify:false})],devServer: {port: 9000}
}
三、自定义tpl-loader
// tpl-loader/index.js 文件:
function tpl(source){console.log(source);// 去掉所有空格source = source.replace(/\s+/g, '');return `export default (options) => {${compilerDom.toString()}return compilerDom('${source}',options);}`
}// 替换{{}}内部内容function compilerDom(source,replaceObj){const result = source.replace(/\{\{(.*?)\}\}/g,function(node,key){return replaceObj[key]})return result
}module.exports = tpl;