Home > Web Front-end > JS Tutorial > body text

webpack loader practice

PHP中文网
Release: 2017-06-22 11:00:00
Original
1545 people have browsed it

Developers who are new to the concept of front-end templates have usually used underscore's template method. It is very simple and easy to use. It supports assignment, conditional judgment, looping, etc., and can basically meet our needs.

When using Webpack to build a development environment, if we want to use underscore's template method to render the front-end template, we can save the template code independently in the template file. How to load the template file into our JavaScript for template rendering has become the first problem we need to solve.

Speaking of this, we must mention the concept of loader in Webpack. Webpack supports converting the resource files of the application through the loader method, and Our template files also need corresponding loaders to load in order to support our development.

Leftstick in segmentfault mentioned that raw-loader, html-loader, template-html-loader, and ejs-loader can currently support template loading. . . . . . [Refer to templating for more lists]

Different loaders are slightly different, which is reflected in the performance in the JS code after loading. Some return strings, and some return JS objects or method.

We try to use raw-loader to handle it. The official explanation of raw-loader is [Load the file as a string], so we can The template file is loaded into a string, and then underscore is used to render the final HTML.

We use the following configuration to simply build a webpack environment.

package.json

{  "name": "tpl-webpack",  "version": "1.0.0",  "description": "",  "main": "index.js?1.1.10",  "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"
  }
}
Copy after login

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()]
};
Copy after login

Template code index. tpl

<% _.each(data, function(n){ %><p>姓名:<%= n.name %>,年龄:<%= n.age %>,性别:<%= n.sex %></p><% }); %>
Copy after login

index.js

 1 var _ = require('underscore'); 2  3 // 这里可以看到indexTplFile只是字符串 4 var indexTplStr = require('./index.tpl'); 
 5 // template方法将其封装成一个方法 6 var indexTpl = _.template(indexTplStr); 7   8 var data = [ 9     {10         name: 'mike',11         age: 18,12         sex: '男'13     },14     {15         name: 'nina',16         age: 20,17         sex: '女'18     },19     {20         name: 'elle',21         age: 26,22         sex: '女'23     }24 ];    
25 26 document.body.innerHTML = indexTpl({data:data});
Copy after login
index.js

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

姓名:mike,年龄:18,性别:男

姓名:nina,年龄:20,性别:女

姓名:elle,年龄:26,性别:女
Copy after login

But it can be seen that during 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, continue to tryejs -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         // 提供全局变量_19         new webpack.ProvidePlugin({20             _: "underscore"21         })22     ]23 };
Copy after login

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

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

Through the comparison between raw-loader and ejs-loader, we can have some understanding of the use of webpack's loader, that is, the loader parses different types of files through a certain method. Modularized into our code and then provided to Javascript for further processing.

The above is the detailed content of webpack loader practice. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template