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

How to use the Installation plug-in in practical projects

php中世界最好的语言
Release: 2018-06-09 11:23:06
Original
1381 people have browsed it

This time I will bring you how to use the Installation plug-in in actual projects, and what are the precautions for using the Installation plug-in in actual projects. The following is a practical case, let's take a look.

This plugin is used to simplify the creation of HTML files that serve webpack bundles, especially when the file name contains a hash value, and this value changes every time it is compiled. You can either let this plugin help you automatically generate HTML files, use lodash templates to load the generated bundles, or load the bundles yourself.

How to use the Installation plug-in in actual projects

Use npm to install this plug-in

$ npm install html-webpack-plugin@2 --save-dev
Copy after login

Basic Usage

This plugin can help generate HTML files. In the body element, use script to include all your webpack bundles. Just configure the following in your webpack configuration file:

var HtmlWebpackPlugin = require('html-webpack-plugin')
var webpackConfig = {
 entry: 'index.js',
 output: {
  path: 'dist',
  filename: 'index_bundle.js'
 },
 plugins: [new HtmlWebpackPlugin()]
}
Copy after login

This will automatically be included in dist A file named index.html is generated in the directory with the following content:

<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <title>Webpack App</title>
 </head>
 <body>
  <script src="index_bundle.js"></script> 
 </body>
</html>
Copy after login

If you have multiple webpack entry points, they will all be included in the generated script element.

If there are any CSS resources included in the webpack output (for example, css extracted using ExtractTextPlugin), these will be included in the head element of the HTML page using links.

Configuration

A series of configurations can be performed, supporting the following configuration information

  1. title: used to generate pages title element

  2. filename: The name of the output HTML file. The default is index.html. It can also be directly configured with a subdirectory.

  3. template: Template file path, supports loader, such as html!./index.html

  4. inject: true | 'head' | 'body' | false , inject all resources into a specific template or templateContent. If set to true or body, all javascript resources will be placed at the bottom of the body element, and 'head' will be placed in the head element.

  5. favicon: Add specific favicon path to the output HTML file.

  6. minify: {} | false, pass html-minifier option to minify output

  7. hash: true | false, if true, will Adds a unique webpack build hash to all included scripts and CSS files, useful for uncaching.

  8. cache: true | false, if true, this is the default value and the file will only be published after the file is modified.

  9. showErrors: true | false, if true, this is the default value and the error message will be written to the HTML page

  10. chunks: Allows adding only certain chunks (for example, only unit test chunks)

  11. chunksSortMode: Allows to control how chunks are sorted before being added to the page, supported values: 'none' | 'default ' | {function}-default:'auto'

  12. excludeChunks: Allows skipping certain chunks (for example, skipping unit test chunks)

The following examples demonstrate how to use these configurations.

{
 entry: 'index.js',
 output: {
  path: 'dist',
  filename: 'index_bundle.js',
  hash: true
 },
 plugins: [
  new HtmlWebpackPlugin({
   title: 'My App',
   filename: 'assets/admin.html'
  })
 ]
}
Copy after login

Generate multiple HTML files

Generate multiple HTML files by adding this plug-in multiple times in the configuration file.

{
 entry: 'index.js',
 output: {
  path: 'dist',
  filename: 'index_bundle.js'
 },
 plugins: [
  new HtmlWebpackPlugin(), // Generates default index.html 
  new HtmlWebpackPlugin({ // Also generate a test.html 
   filename: 'test.html',
   template: 'src/assets/test.html'
  })
 ]
}
Copy after login

Write a custom template

If the default generated HTML file does not suit your needs, you can create your own custom template. A convenient way is to pass the inject option and then pass it to a custom HTML file. html-webpack-plugin will automatically inject all required CSS, js, manifest and favicon files into the markup.

plugins: [
 new HtmlWebpackPlugin({
  title: 'Custom template',
  template: 'my-index.html', // Load a custom template 
  inject: 'body' // Inject all scripts into the body 
 })
]
Copy after login

my-index.html file

<!DOCTYPE html>
<html>
 <head>
  <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
  <title><%= htmlWebpackPlugin.options.title %></title>
 </head>
 <body>
 </body>
</html>
Copy after login

If you have a template loader, you can use it to parse this template.

module: {
 loaders: [
  { test: /\.hbs$/, loader: "handlebars" }
 ]
},
plugins: [
 new HtmlWebpackPlugin({
  title: 'Custom template using Handlebars',
  template: 'my-index.hbs',
  inject: 'body'
 })
]
Copy after login

Also, if your pattern is a string, you can pass it using templateContent.

plugins: [
 new HtmlWebpackPlugin({
  inject: true,
  templateContent: templateContentString
 })
]
Copy after login

If the inject feature doesn't suit your needs, you want full control over resource placement. You can use lodash syntax directly, using default template as a starting point to create your own template.

The templateContent option can also be a function to use other languages, such as jade:

plugins: [
 new HtmlWebpackPlugin({
  templateContent: function(templateParams, compilation) {
   // Return your template content synchronously here 
   return '..';
  }
 })
]
Copy after login

or the asynchronous version

plugins: [
 new HtmlWebpackPlugin({
  templateContent: function(templateParams, compilation, callback) {
   // Return your template content asynchronously here 
   callback(null, '..');
  }
 })
]
Copy after login

Note that if template and templateContent are used at the same time, the plugin will Throw an error.

变量 o 在模板中是在渲染时传递进来的数据,这个变量有如下的属性:

1、htmlWebpackPlugin: 这个插件的相关数据 ◦

htmlWebpackPlugin.files: 资源的块名,来自 webpack 的 stats 对象,包含来自 entry 的从 entry point name 到 bundle 文件名映射。

"htmlWebpackPlugin": {
 "files": {
  "css": [ "main.css" ],
  "js": [ "assets/head_bundle.js", "assets/main_bundle.js"],
  "chunks": {
   "head": {
    "entry": "assets/head_bundle.js",
    "css": [ "main.css" ]
   },
   "main": {
    "entry": "assets/main_bundle.js",
    "css": []
   },
  }
 }
}
Copy after login

如果在 webpack 配置文件中,你配置了 publicPath,将会反射正确的资源

htmlWebpackPlugin.options: 传递给插件的配置。

2、webpack: webpack 的 stats 对象。

3、webpackConfig: webpack 配置信息。

过滤块

可以使用 chunks 来限定特定的块。

plugins: [
 new HtmlWebpackPlugin({
  chunks: ['app']
 })
]
Copy after login

还可以使用 excludeChunks 来排除特定块。

plugins: [
 new HtmlWebpackPlugin({
  excludeChunks: ['dev-helper']
 })
]
Copy after login

事件

通过事件允许其它插件来扩展 HTML。

  1. html-webpack-plugin-before-html-processing

  2. html-webpack-plugin-after-html-processing

  3. html-webpack-plugin-after-emit

使用方式:

compilation.plugin('html-webpack-plugin-before-html-processing', function(htmlPluginData, callback) {
 htmlPluginData.html += 'The magic footer';
 callback();
});
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

vue-cli组件导入使用步骤详解

使用webpack做出ReactApp

The above is the detailed content of How to use the Installation plug-in in practical projects. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!