loader practice of Web pack

Keywords: Javascript Webpack JSON npm

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

 1 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});
index.js

 

After running npm install, run webpack and open index.html, you can see the following results.

Name: mike, age: 18, gender: male

Name: nina, age: 20, gender: female

Name: elle, age: 26, gender: female

But you can see that in the process of rendering the template, three lines of code are executed. If we want to generate the final HTML string with only one line of code, we will continue to try ejs-loader.

webpack.config.js

 1 var webpack = require('webpack');
 2 var HtmlWebpackPlugin = require('html-webpack-plugin');
 3 module.exports = {
 4     entry: './index.js',
 5     output: {
 6         filename: 'bundle.js'
 7     },
 8     module: {
 9         loaders:[ 
10             { 
11                 test: /\.tpl$/, 
12                 loader: 'ejs-loader?variable=data'
13             },
14         ]
15     }, 
16     plugins: [ 
17         new HtmlWebpackPlugin(),
18         // Providing global variables_
19         new webpack.ProvidePlugin({
20             _: "underscore"
21         })
22     ]
23 };

It's also very simple to use in code. After require's corresponding tpl file, you can directly render the corresponding html template.

var indexTpl = require('./index.tpl');
document.body.innerHTML = indexTpl(data);

By comparing raw-loader with ejs-loader, we can get some insight into the use of Web pack loader, that is, loader modularizes different types of files into our code through some parsing method, and then provides Javascript with further processing.

Code address: https://github.com/gebin/underscore-tpl-loader-demo

Posted by BlueBoden on Thu, 20 Jun 2019 16:47:11 -0700