configuration
Absolute path Configures loader
// webpack.config.js
{
test: /\.js$/
use: [
{
loader: path.resolve('loaders/myLoader1.js'),
options: {name:'myLoader1'}
},
{
loader: path.resolve('loaders/myLoader2.js'),
options: {name:'myLoader2'}
}
]
},
{
test: /\.less$/,
use:[
{
loader:'style_loader'
},
{
loader:'less_loader'
}
]
}
Copy the code
Use the Resolveloader.modules configuration for automatic search
// webpack.config.js
resolveLoader: {
modules: [
'node_modules',
path.resolve(__dirname, 'loaders')
]
}
Copy the code
Write the usage
- Loader is a function that is called by Loader Runner, and the loader API is called by this inside the function. Therefore, the Loader function cannot use the arrow function
- Loader receives three parameters: source(the content of the resource file), map(sourcemap),meta(abstract syntax tree AST)
- There must be a return value, or a callback return value
A simple example
module.exports = function(source,map,meta){ console.log(source,this.query) this.callback(null,source,map,meta) // return Import b from './b.js'; export default 'aaaaa'+b { name: 'myloader2' } import b from './b.js'; export default 'aaaaa'+b { name: 'myloader1' } import c from './c.js'; export default 'bbbbbbb'+c; { name: 'myloader2' } import c from './c.js'; export default 'bbbbbbb'+c; { name: 'myloader1' } export default 'cccccccccccccc'; { name: 'myloader2' } export default 'cccccccccccccc'; { name: 'myloader1' } */Copy the code
Less_loader sample
Note: Install less first
var less = require('less')
module.exports = function(source){
var callback = this.async();
less.render(source).then(function(output){
// console.log('less------------',output.css)
callback(null,JSON.stringify(output.css),output.map)
})
}
Copy the code
Style_loader sample
module.exports = function(source){
return `
;(function(){
var head = document.createElement('style');
head.innerHTML = ${source}
document.getElementsByTagName('head')[0].appendChild(head)
})();
`
}
Copy the code
reference
- www.webpackjs.com/contribute/…
- www.webpackjs.com/api/loaders…
- Less.bootcss.com/usage/#prog…
- Github:github.com/logmei/fron…