Extension Htmlwebpackplugin inserting a custom script

Source: Internet
Author: User

Webpack provides an introduction to how to develop a Webpack plugin that you can view directly here, providing an example of an extended htmlwebpackplugin development.

Before we introduced Htmlwebpackplugin, this plugin allows webpack dynamically packaged output to be injected into the page, but sometimes we need to inject some custom stylesheets or scripts into this page htmlwebpackplugin This feature is not supported. A suggestion was made to the plugin author, and here is what is discussed, and the result is that the plugin provides several events to support itself to implement this feature. We demonstrate how to use these events to extend the webpack with an example.

Demand

We want to be able to automatically insert script scripts before webpack generated script to load our custom data in advance. The last generated HTML is similar to this effect.

    <Scripttype= "Text/javascript"src= "./configuration/config.js"></Script>    <Scripttype= "Text/javascript"src= "Style.bundle.js"></Script>    <Scripttype= "Text/javascript"src= "App.bundle.js"></Script>

The first line is the script we expect to inject, and the other two lines are webpack exported scripts.

Getting Started with plugins

As a Webpack plugin, this is how it works.

plugins: [    new  myplugin ({        paths: ["./configuration/config.js"]    }),     New Htmlwebpackplugin ({        ' Hello angular2! ' ,        '. /src/index.html ',        true    })],

All plug-ins are defined in plugins, an array of plug-ins, each element is an object instance of a plug-in, and what parameters are passed is defined by yourself.

From the way of use can be seen, in fact, we need a javsscript class function, that is to say, write Webpack plug-in is defined as a function, this function needs to receive parameters.

Webpack also requires this object to provide a function called apply, which is defined on the plugin's prototype, Webpack invokes the plugin instance, and when called, passes a parameter so that we can access the Webpack contextual information.

The official provided instance function is as follows, and the last line is to export the plugin using the CommonJs style.

function Helloworldplugin (options) {  //  Setup The plugin instance with options ...  function(compiler) {  compiler.plugin(function() {    Console.log ( ' Hello world! ' );    = Helloworldplugin;

Passing parameters

In our requirements, we want to pass a path parameter named paths, where each path requires a SCRIPT element to be inserted before the script exported by Webpack.

New Myplugin ({        paths: ["./configuration/config.js"]    }),

In our plugin, we need to save this parameter in order to use it in the Apply function.

function Myplugin (options) {    //this. options = options;}

Saved directly to the current object instance, this is the plug-in object instance that you just created when you mate with new.

Realize

When Webpack invokes the application method of the plug-in object, we should first get the parameters we saved, use this to access the current object, and get the parameters just saved.

function (compiler) {    //  ...    var  This . options.paths;     };

Within our apply method, we need to call compiler's plugin function. This function registers to the webpack each processing stage, can support the parameter to have:

We used the compilation compilation task here.

function (compiler) {    var  This . options.paths;    Compiler.plugin (function(compilation, options) {

});};

Webpack will provide parameters for the callback function we provide, and we can register events for the compile phase. Html-webpack-plugin provides a series of events.

Async:

    • html-webpack-plugin-before-html-generation
    • html-webpack-plugin-before-html-processing
    • html-webpack-plugin-alter-asset-tags
    • html-webpack-plugin-after-html-processing
    • html-webpack-plugin-after-emit

Sync:

    • html-webpack-plugin-alter-chunks

We can register to use the Html-webpack-plugin-before-html-processing event before it processes HTML.

function (compiler) {    var  This . options.paths;    Compiler.plugin (function(compilation, options) {        compilation.plugin ( function (Htmlplugindata, callback) {
     ......
}); });};

In this callback function, we can get the context object provided by Html-webpack-plugin, for example, the path of the JavaScript file for which the script is to be generated is stored in the htmlPluginData.assets.js array. It generates the script element in turn, based on the path in the array, and then inserts it into the Html page.

All we need is to insert our path in front of this array.

MyPlugin.prototype.apply =function(compiler) {    varpaths = This. options.paths; Compiler.plugin (' Compilation ',function(compilation, options) {Compilation.plugin (' Html-webpack-plugin-before-html-processing ',function(Htmlplugindata, callback) {             for(vari = paths.length-1; I >= 0; i--) {htmlPluginData.assets.js.unshift (paths[i]); } Callback (NULL, Htmlplugindata);    }); });};

The complete plug-in code is shown below.

functionMyplugin (options) { This. options =options;} MyPlugin.prototype.apply=function(compiler) {    varpaths = This. options.paths; Compiler.plugin (' Compilation ',function(compilation, options) {Compilation.plugin (' Html-webpack-plugin-before-html-processing ',function(Htmlplugindata, callback) {             for(vari = paths.length-1; I >= 0; i--) {htmlPluginData.assets.js.unshift (paths[i]); } Callback (NULL, Htmlplugindata);    }); });}; Module.exports= Myplugin;

The last line is to export our plugin.

Discuss

With Webpack's plug-in mechanism, we are free to extend the webpack to achieve the features we need.

See Also:

How to WRITE A PLUGIN

How to write a Webpack plugin (i)

Webpack Use Optimization (Basic article) #2

Html-res-webpack-plugin

Extension Htmlwebpackplugin inserting a custom script

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.