Original address
Write loaders and plugins
github
1、 Loader
1. Introduction to loader
What is loader
Loader is actually a function that converts the matched content and returns the converted result.
Loader function
stay
webpack
inloader
Like a translator.webpack
Only knowJavaScript
This language is used for other resourcesloader
It can be transformed for pretreatment
- The loader is executed in order,
Support chained call
。 The order of loader execution is from bottom to top and from right to left. For example, processing files of style classes,use:['style-loader', 'css-loader']
。css-loader
The processed file is returned tostyle-loader
。 - The responsibility of a loader is single, and only one transformation needs to be completed.
- Webpack will cache the processing results of all loaders by default, and the loaders that have not been modified will not be reloaded. The default cache results of closing webpack need to be added
this.cacheable(false);
Common loaders
- Loader of style class:
CSS loader, style loader, less loader, postcss loader (add WebKit)
etc. - Loader of file class:
url-loader, file-loader, raw-loader
Wait. - Loader of compilation class:
babel-loader, ts-loader
etc. - Verification test class loader:
eslint-loader, jslint-loader
etc.
4. Three ways of using loader
-
-
stay
webpack.config.js
Medium configurationmodule.exports = { module:{ rules:[{ test:/\.css$/, use:['css-loader'], // use:{loader:'css-loader',options:{}} } ] } }
-
-
-
Through the parameter mode of the command line
webpack --module-bind 'css=css-loader'
-
-
-
Use inline
import txt from 'css-loader!./file.css';
-
2. Write a loader
Idea: as we said earlier
1. Loader is a function; 2. Convert the matched content; 3. Return the converted content
, according to this idea, we can write the simplestloader
//Yes/ loader/replaceLoader. JS creates a loader that replaces the string
module.exports = function(source) {
return source.replace('a', 'b')
}
//On webpack config. JS uses its own loader
module.exports = {
module:{
rules:[{
test:"/\.js$/",
use:[{
loader: path.resolve(__dirname, './loader/replaceLoader.js')
options:{
Name: 'Lin 11'
}
}
]
}]
}
}
//Or use replaceloader
module.exports={
resolveLoader:['node_modules', './loader']
module:{
rules:[{
test:"/\.js$/",
use:['resolveLoader']
}]
}
}
The above is the simplest case of writing loader
-
The loader can also receive
options
The parameters passed in. See the detailsloader API, you can also use the officialloader-util
Receive parametersconst loaderUtil = require('loader-utils') module.exports = function(source) { console. Log (this. Query. Name) // Lin 11 const options = loaderUtil.getOptions(this) return source.replace('a', 'b') }
-
Asynchronous: loader is a function. Naturally, there is a distinction between synchronous and asynchronous. Using asynchronous loaders requires adding
this.async()
Declare asynchronous operationconst loaderUtils = require('loader-utils') module.exports = function(source) { const options = loaderUtils.getOptions(this) const callback = this.async() setTimeout(()=>{ console.log(options.name) let res = source.replace('a', options.name) callback(null, res, sourceMaps, ast) }, 4000) }
The above code will be packaged successfully in 4 seconds. If not
this.async()
The asynchronous operation will fail,callback()
The callback function puts the result back. - By default, the string code passed by webpack to the loader is
utf-8
, if you need to process binary files, you need to addexports.raw = true
。 - As mentioned above, webpack will default to
loader
The load result cache of is closed if necessarywebpack
The cached results need to be addedthis.cacheable(false);
。 Npm link
It is specially used to develop and debug the local NPM module. It can also be in the local mode without publishing it to NPMloader
。 Specific needs inpackage.json
Medium configurationLocal loader
, execute under the root directorynpm link loader-name
Can be innode_modules
Use local inloader
Yes. At the same time, the above method can also be usedresolveLoader
Implement importloader
Way of
Summarize the idea of writing loader
- Loader is an export function with return value, which can be implemented with the help of third-party modules and node APIs.
- Loader can use
loader-utils
Receivedoptions
Parameters passed from- The asynchronous writing of loader requires the declaration to be displayed
const callback = this.async()
Indicates asynchrony.- If the loader needs to handle binary files, it also needs to declare
exports.raw = true
- The allowed results of the loader will be cached by the webpack and closed if necessary
webpack
The cache result of needs to be declaredthis.cacheable(false)
- Written local
loader
Can helpNpm link
orresolveLoader
Import.
2、 Construction process of webpack
Before talking about plugins, you need to know what the construction process of webpack is
Initialization parameters
。 From profiles andshell
Merged parameters in statementStart compilation
。 Initialize the parameters obtained in the previous step toComplier object
, load all import plug-ins, execute the run method of the object and start compiling;Determine the entrance
。 From configuredentry
The portal finds all the portal files.Compilation module
。 Call all configured according to the dependency of the entry fileloader
Convert.Complete module compilation and output
。 Code blocks are formed according to the dependencies between entry fileschunk
。Output complete
。 Code block to be formedchunk
Output to file system.
Formed by initialization above
complier
Object will be injected into the plug-inapply(complier)
Inside.complier
The object contains all the configuration information of the webpack environment, such asoptions, loaders, plugins
And so on, you can simply thinkcomplier
Is an instance of webpack, which can be accessed throughcompler.plugin()
Can monitorwebpack
Broadcast events.
3、 Plugin
1. Introduction to plugin
What is a plugin
Plugin is a plug-in, which is a class based on the event flow framework
Tapable
realization. In the construction process of webpack, after initializing the parameters, all the parameters will be loadedplugin
Plug in, create an instance of the plug-in.
Plugin function
plugin
It can be involved through the hookwebpack
The whole event flow. in other wordsplugin
You can use these life cycle hooks at the right timewebpack
The provided API does something.
Common plugins
html-webpack-plugin
Will automatically generate one after packaginghtml
File, and the packaged JS file will be imported intohtml
In the document.optimize-css-assets-webpack-plugin
Compress CSS code.mini-css-extract-plugin
。 Will writestyle
The CSS in the tag is separated into onelink
Import the generated CSS filewebpack-parallel-uglify-plugin
。 Enable multi process code compression to improve the speed of packaging.clean-webpack-plugin
。 Delete the old generated files before each package.serviceworker-webpack-plugin
。 Add offline caching function for web applications.
How to use plugin
stay
plugins
Used in
const ServiceworkerWebpackPlugin = require('serviceworker-webpack-plugin')
module.exports = {
plugins:[
new ServiceworkerWebpackPlugin(),
]
}
2 write a plugin
Idea:
plugins
Is a class,webpack
There are many built-in for pluginapi, it needs to be defined on the prototypeapply(compliers)
Function. Also specify the to mountwebpack
Hook.
class MyPlugin {
constructor(params){
console.log(params)
}
//After webpack initializes the parameters, it will call this reference function to break into the initialized complier object.
apply(complier){
//Bind hook event
// complier.hooks.emit.tapAsync()
compiler.plugin('emit', compilation => {
console.log('MyPlugin')
))
}
}
module.export = MyPlugin
Compilation object
It contains the current module resources, compilation generation resources, and files that can monitor changes. After each file changes, acompilation
Object, bycompilation
Can also readcompiler
Object.
modeplugin
You can use node’s modal tool topackage.json
Add in"debug":"node --inspect --inspect brk node_modules/webpack/bin/webpack.js"
Summarize the idea of writing plugin
- Write a class.
- Define an apply method in the class.
- In application method
apply()
Specified mounted inwebpack
event hookcomplier.hooks.
。- Process specific data for webpack internal instances.
- Call the callback provided by webpack after the function is completed.
4、 Interview questions
1. The difference between loader and plugin
- Loader is a function used to match a specific module, convert the received content and return it. stay
webpack
Operate files in and act as a file converter. staymodules.rules
Configuration in.- Plugin is a plug-in that does not directly manipulate files and is based on the event flow framework
Tapable
realization,plugin
It can be involved through the hookwebpack
The whole event flow. in other wordsplugin
You can use these life cycle hooks at the right timewebpack
The provided API does something. stayplugins
Configuring plug-ins in
2. Writing ideas of loader
Ginseng
3. Writing ideas of plugin
Ginseng
4. Difference between complier and compilation
- The complier object exposes the hooks related to the whole life cycle of the webpack, which is
webpack
The product of initialized parameters, includingoptions, entry, plugins
And other attributes can be simply understood aswebpack
An example of.compilation
Object iscomplier
An example is every timewebpack
Lifecycle objects in the build process. One can be generated after each file changescomplition
Object.
Summary: both objects have their own life cycle hooks,Compilation object
Responsible for smaller granularity life cycle hooks.Compiler object
It is the object of a whole life cycle hook of webpack.
reference resources
Introduction to loader and plugin of webpack