如何寫一個Loader

如何寫一個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/

https://webpack.js.org/concepts/loaders/

https://glebbahmutov.com/blog/writing-webpack-loader/

?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容