While browsing the web for various Webpack optimizations, I came across an API like this
cache-loader
The loader is used for
If the content of a file remains unchanged, the parsed result remains unchanged after the same loader parses the file. Using cache-loader, you can save the parsed result of loader so that subsequent parses can directly use the saved result
So I used it in the code
module.exports = {
module: {
rules: [{test: /\.js$/,
use: [{
loader: "cache-loader".options: {
cacheDirectory: "./cache" // Where cached files are stored (default system provides temporary files)}},... loaders] } ] } }Copy the code
The cache-loader saves the parse result in the first place because it is parsed by other loaders
Cause: Generally, the loader execution sequence is from right to left and from bottom to top.
At this point, the problem arises
Cache-loader is the last bit of the compiler to cache the compiled result, but when it comes to the second compilation, the loader is also compiled from the back to the front, and finally to the cache-loader. How does it skip the previous loaders and print the cached compilation directly
There is also a.pitch method that needs to be executed before the loader can be executed
Loader execution sequence
use: ["loader1", "loader2", "loader3"]
Before the loader actually processes the code, the file address is passed to the positional-direction loader.pitch method, which determines whether to return or not
function loader(source) {
return `new source`
}
loader.pitch = function(filePath) {
// Can return with or without return
// If it returns, the source code is returned directly and the next step of the code execution is controlled
}
Copy the code
The cache-loader execution sequence can be sorted out:
First compilation:
- The file path is passed to loader.pitch, but no return is returned. Perform subsequent operations
- The code is processed by multiple loaders and a cache file is generated by the final cache-loader(loader1)
If the file path is compiled to loader.pitch for the second time and the corresponding cache file is found, the subsequent execution is skipped and the cache file code is directly returned
Summary: Many Webpack loaders are handled through the. Pitch method, which aims to control the output code content and control the execution process; For example, style-loader also uses the.pitch method to handle dynamically executed functions, which is an extension point
This article through a cache-loader to introduce loader execution sequence hidden. Pitch method, difficulty is not high, easy to understand. As my debut article to improve themselves, there are inappropriate places welcome to leave a message and comment ~~~~~~~