项目目录如下:
只对主要的核心部分进行展示
package.json (注:这里到的是webpack4版本!)
{
"name": "templateengine",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "webpack-dev-server"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"webpack": "^4.46.0",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.3"
}
}
webpack.config.js
const path = require("path");
module.exports = {
// 模式
mode: "development",
// 入口文件
entry: "./src/index.js",
// 打包路径
output: {
filename: "bundle.js",
},
devServer: {
// 静态资源
contentBase: path.join(__dirname, "www"),
// 不压缩
compress: false,
// 端口
port: 8080,
// 虚拟打包路径
publicPath: "/xuni/",
},
};
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>mustache源码手写</title>
</head>
<body>
<script src="/xuni/bundle.js"></script>
<script>
const templateStr = `
<ul>
{{#arr}}
<li>
<div>学生{{name}}的爱好</div>
{{#hobbies}}
<ol>{{.}}</ol>
{{#list}}
<p>{{.}}</p>
{{/list}}
{{/hobbies}}
</li>
{{/arr}}
</ul>
`;
const data = {};
Mustache.render(templateStr, data);
</script>
</body>
</html>
index.js
window.Mustache = {
render(tempStr, data) {
console.log(tempStr, data);
},
};
启动项目 注: 这里npm run dev 需要对应package.json中的配置哦!是通过webpack-dev-server启动本地服务
npm run dev
此时通过浏览器打开 http://localhost:8080/ 在控制台输出看到如上图就说明我们环境配置好了!