This is the 24th day of my participation in Gwen Challenge
[Webpack series of articles in serial…]
Loader enables Webpack to handle non-javascript files (WebPack itself only understands JavaScript). Loader can convert all types of files into valid modules that WebPack can handle, and then you can take advantage of WebPack’s packaging capabilities to process them.
In essence, WebPack Loader converts all types of files into modules that the application’s dependency diagram (and ultimately its bundle) can reference directly.
Loader nature
Loader is simply a JavaScript module exported as a function. There are synchronous and asynchronous Loaders.
- Synchronous loader
Exports = function(content,map,meta){return someSyncOperation(content)}Copy the code
- Asynchronous loader
Module.exports = function(content,map,meta){var callback = this.async() {var callback = this.async(); someAsyncOperation(content, function(err, result) { if (err) return callback(err); callback(null, result, map, meta); }); }Copy the code
Loader execution sequence
Loader configuration:
module.exports = {
module:{
rules:[
{
test:/\.less$/,
use:[
'style-loader',
'css-loader',
'less-loader'
]
}
]
}
}
Copy the code
The loaders are executed sequentially, from the back to the front, because Webpack uses the Compose function composition:
Var compose = (compose, compose, compose, compose, compose, compose, compose, compose, compose, compose, compose, compose) FNS)=>{return (arg)=> ferns.reduce ((promise,fn)=>promise.then(fn), promise.resolve (arg))} var item1 = (x)=>{return new Promise((resolve)=>{ setTimeout(()=>{ console.log('1') resolve(x) },1000) })} var item2 = (y)=>{return new Promise((resolve)=>{ setTimeout(()=>{ console.log('2') resolve(y+3) },5000) })} var a = Compose (item1,item2) a(5). Then (console.log) : compose(item1, Item2) a(5)Copy the code
The Row – the realization of the loader
// raw-loader.js module.exports = function(source){const json = json.stringify (source) Replace (/\u2028/g,'\\u2028'). Replace (/\u2029/g,'\\u2029') return 'export default ${json}'}Copy the code
Loader-runner Debugging tool
Loader, unlike Plugin, can be developed and debugged independently of WebPack.
- The installation
npm install loader-runner --save-dev
Copy the code
Using the example
Import {runLoaders} from "loader-runner"; Const fs = require('fs') const path = require('path') runLoaders({// The absolute path of the resource (can add query string, such as? Loaders :[path.resolve(__dirname,'./loader/raw-loader.js')], / / additional context loader context based outside of the context: {minimize: true}, / / read the resource function readResource: fs. ReadFile. Bind (fs)}, function(err,result){ err? Console. log(err):console.log(result)}) // Run the test node test-loader.jsCopy the code
How to handle exceptions in loader? Use cache to generate a file. For details, see: Loader API official document
conclusion
So far we have learned the use of Loader.