Developers who first understand the concept of front-end template usually use the template method of underscore, which is very simple and easy to use. It supports assignment, conditional judgment, cycling and so on. It can basically meet our needs.
When using Webpack to build a development environment, if we want to use the template method of underscore to render the front-end template, we can save the template code independently into the template file. How to load template files into our JavaScript for template rendering has become the first problem we need to solve.
Here, we must mention the concept of loader in Web pack. Web pack supports the transformation of resource files of applications through loader, and our template files need the corresponding loader to load in order to support our development.
In segmentfault, leftstick talks about raw-loader, html-loader, template-html-loader, ejs-loader... which can support template loading at present. [More list references templating]
Different loaders have slightly different performances in JS code after loading, some are returned strings, some are JS objects or methods.
We try to use raw-loader to process it. The official interpretation of raw-loader is [load files as strings], so we can load template files into strings and then use underscore to render the final HTML.
We use a simple configuration to build a web pack environment.
package.json
{ "name": "tpl-webpack", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "devDependencies": { "html-webpack-plugin": "^2.28.0", "raw-loader": "^0.5.1", "underscore": "^1.8.3", "webpack": "^3.0.0" } }
webpack.config.js
var HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './index.js', output: { filename: 'bundle.js' }, module: { loaders:[ { test: /\.tpl$/, use: 'raw-loader' } ] }, plugins: [new HtmlWebpackPlugin()] };
Template code index.tpl
<% _.each(data, function(n){ %> <p>Full name:<%= n.name %>,Age:<%= n.age %>,Gender:<%= n.sex %></p> <% }); %>
index.js
index.js1 var _ = require('underscore'); 2 3 // Here you can see indexTplFile It's just a string. 4 var indexTplStr = require('./index.tpl'); 5 // template Method encapsulates it into a method 6 var indexTpl = _.template(indexTplStr); 7 8 var data = [ 9 { 10 name: 'mike', 11 age: 18, 12 sex: 'male' 13 }, 14 { 15 name: 'nina', 16 age: 20, 17 sex: 'female' 18 }, 19 { 20 name: 'elle', 21 age: 26, 22 sex: 'female' 23 } 24 ]; 25 26 document.body.innerHTML = indexTpl({data:data});