如何写一个Loader
由于webpack只能解析Javascript与JSON语句。于是webpack加入了Loader的概念。
Loader用于将其他语言转化为能被webpack理解的模块。
// Loader的基础使用:
const path = require('path');
module.exports = {
module: {
rules: [{ test: /\.txt$/, use: 'raw-loader' }],
},
};
接下来我们写一个简单的loader。
首先新建一个项目并导入webpack。
yarn init
yarn add webpack webpack-cli
添加index.js与一个转化目标/fish/index.fish
// index.js
import Fish from './fish/index.fish'
console.log(Fish)
// /fish/index.fish
I'm byFish
添加一个自定义的Loader文件
// /loader/index.js
module.exports = function(source) {
return `export default ${JSON.stringify(source)}`
}
添加webpack.config.js文件,配置webpack
const path = require('path');
module.exports = {
entry: './index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
},
mode: 'production',
module: {
rules: [
{
test: /\.fish$/,
use: [
{
loader: path.resolve('loader/index.js'),
options: {
/* ... */
},
},
],
},
],
},
};
在package.json中加入构建命令
{
...
"scripts": {
"build": "webpack"
}
...
}
运行后查看/dist/bundle.js,已成功编译。
(()=>{"use strict";console.log("I'm byFish")})();
在webpack.config.js可以加入options字段,传递参数。Loader中使用this.getOptions()可以接收到
// webpack.config.js
options: {
addEnd: true,
}
// loader文件
module.exports = function(source) {
const {addEnd} = this.getOptions()
const result = `"${JSON.stringify(source).slice(1, -1)}${addEnd ? ' end' : ''}"`
return `export default ${result}`
}
输出将变成
(()=>{"use strict";console.log("I'm byFish end")})();
在异步或者更复杂的情况下Loader可以使用this.callback()
来返回值。
参考
https://webpack.js.org/contribute/writing-a-loader/