學習webpack loader,最後模擬style-loader、less-loaderjavascript
{
test: /\.js$/
use: [
{
loader: path.resolve('path/to/loader.js'),
options: {/* ... */}
}
]
}
複製代碼
resolveLoader: {
modules: [
'node_modules',
path.resolve(__dirname, 'loaders') //本身開發的loaders
]
}
複製代碼
//css-loader 把css解析成webpack識別的模塊
module.exports = function(source) {
return `module.exports=${source}`;
}
複製代碼
{
test:/\.less$/,
use:[
'style-loader','css-loader','less-loader'
]
}
複製代碼
const less = require('less');
module.exports = function (source) {
less.render(source, (e, output)=>{
this.callback(e,output.css); //把編譯後的css返回給下一個loader
});
};
複製代碼
module.exports = function (source) {
return source; //source是上個loader的返回值,若是沒有上一個loader,則是css的內容
};
複製代碼
module.exports = function (source) {
return `const e = document.createElement('style'); e.innerHTML = ${JSON.stringify(source)}; document.head.appendChild(e);`;
};
複製代碼
webpack loader的功能遠不止這些,本文算是編寫loader的"套路"入門篇。css