# tpl-loader-creator **Repository Path**: gaotengjun/tpl-loader-creator ## Basic Information - **Project Name**: tpl-loader-creator - **Description**: 简单webpack、loader, 将tpl模板编译后添加到页面中 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2022-04-27 - **Last Updated**: 2025-03-07 ## Categories & Tags **Categories**: Uncategorized **Tags**: JavaScript ## README ## 1. 初始化项目 ```json { "name": "tpl-loader-creator", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "webpack-dev-server" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.17.9", "babel-loader": "^8.2.5", "webpack": "^4.30.0", "webpack-cli": "^3.3.0", "webpack-dev-server": "^3.7.2", "html-webpack-plugin": "4.0.0" } } ``` - 安装babel-loader和相关依赖 ```css yarn add babel-loader @babel/core html-webpack-plugin@4.0.0 -D ``` ## 2. webpack配置 - 使用自定义的loader处理tpl文件 - 处理完毕后再次交给babel-loader处理 - options为处理tpl文件时所传入的参数 ```css /*** * mode development 开发环境 production 生产环境 * entry 入口文件 * output path filename 打包输出路径 * devtool source-map 调试工具 * module rules loader * plugin 插件 * devServer 开发服务器 */ const { resolve } = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { mode: 'development', entry: resolve(__dirname, 'src/app.js'), output: { path: resolve(__dirname, 'build'), filename: 'app.js', }, devtool: 'source-map', module: { rules: [ { test: /\.tpl$/, use: [ 'babel-loader', // 自己的loader处理完后 交给babel-loader处理 { loader: './loaders/tpl-loader', // 自己的loader options: { log: true } } ] } ] }, plugins: [ new HtmlWebpackPlugin({ template: resolve(__dirname, 'index.html') // 配置模板文件 }) ], devServer: { port: 3333 } } ``` ## 3. 工具方法 ```css function tplReplace(template, replaceOject) { return template.replace(/\{\{(.*?)\}\}/g, (node, key) => { return replaceOject[key]; }); } module.exports = { tplReplace } ``` ## 4. 模板内容 ```css
{{ age }}
{{ career }}
{{ hobby }}
{{ test }}
{{age}}
{{career}}
{{hobby}}
{{test}}