Webpack val-loader

2023-05-23 09:35 更新

一個webpack加載器,它執(zhí)行給定的模塊,并且在構(gòu)建時返回執(zhí)行結(jié)果,當包中需要該模塊時。通過這種方式,加載程序?qū)⒛K從代碼更改為結(jié)果。

另一種查看方式val-loader是,它允許用戶創(chuàng)建自己的自定義加載器通訊,而無需編寫自定義加載器。

使用兩個參數(shù)調(diào)用目標模板:( options, loaderContext)

  • options添加加載器選項(例如在webpack配置中提供。請參閱下面的示例)。
  • :loaderContext加載程序上下文。

入門

首先,您需要安裝val-loader

$ npm install val-loader --save-dev

然后將加載器添加到您的webpack配置中。例如:

目標文件.js

module.exports = (options, loaderContext) => {
  return { code: "module.exports = 42;" };
};

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /target-file.js$/,
        use: [
          {
            loader: `val-loader`,
          },
        ],
      },
    ],
  },
};

源碼/entry.js

const answer = require("target-file");

 通過webpack您喜歡的方法運行。

選項

姓名 類型 默認 描述
executableFile {String} undefined 允許指定可執(zhí)行文件的路徑

可執(zhí)行文件

類型:String默認:undefined

允許指定可執(zhí)行文件的路徑

數(shù)據(jù).json

{
  "years": "10"
}

可執(zhí)行文件.js

module.exports = function yearsInMs(options, loaderContext, content) {
  const { years } = JSON.parse(content);
  const value = years * 365 * 24 * 60 * 60 * 1000;

  return {
    cacheable: true,
    code: "module.exports = " + value,
  };
};

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.(json)$/i,
        rules: [
          {
            loader: "val-loader",
            options: {
              executableFile: path.resolve(
                __dirname,
                "fixtures",
                "executableFile.js"
              ),
            },
          },
        ],
      },
      {
        test: /\.json$/i,
        type: "asset/resource",
      },
    ],
  },
};

返回對象屬性

此加載器的目標模塊必須導出一個函數(shù)返回對象或Promise解析對象(例如異常步數(shù))的對象,代碼至少包含一個屬性,但可以包含任意數(shù)量的附加屬性。

代碼

類型:String|Buffer默認:undefined 必填

代號傳給 webpack 或?qū)⑻鎿Q模塊的下一個加載器。

資源地圖

類型:Object默認:undefined

傳給 webpack 或下一個加載器的源映像。

AST

類型:Array[Object]默認:undefined

將傳給下一個加載程序的拖象語法樹。如果下一個加載程序使用相同的AST,則有助于加速構(gòu)建時間。

依賴關(guān)系

類型:Array[String]默認:[]

文件依賴項的絕對本地路徑數(shù)組,webpack應監(jiān)視這些路徑以進行更改。

也可以使用添加依賴項loaderContext.addDependency(file: string)。

上下文依賴

類型:Array[String]默認:[]

目錄依賴項的絕對本地路徑數(shù)組,webpack應監(jiān)視這些路徑以進行更改。

也可以使用添加上下面的依賴項loaderContext.addContextDependency(directory: string)。

建立依賴關(guān)系

類型:Array[String]默認:[]

目錄依賴項的絕對本地路徑數(shù)組,webpack應監(jiān)視這些路徑以進行更改。

也可以使用添加構(gòu)建依賴項loaderContext.addBuildDependency(file: string)。

可緩存的

類型:Boolean默認:false

如果是真的,指定代碼可以在監(jiān)視模式下重新使用,如果沒有更更改的依賴項。

例子

簡單的

在此示例中,加載程序配置為對文件名進行運行計算years-in-ms.js, 執(zhí)行代碼,并將結(jié)果作為執(zhí)行結(jié)果存儲在包中。此示例年作傳option,對應于years目標模塊導出函數(shù)中的參數(shù)

多年的 ms.js

module.exports = function yearsInMs({ years }) {
  const value = years * 365 * 24 * 60 * 60 * 1000;

  // NOTE: this return value will replace the module in the bundle
  return {
    cacheable: true,
    code: "module.exports = " + value,
  };
};

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: require.resolve("src/years-in-ms.js"),
        use: [
          {
            loader: "val-loader",
            options: {
              years: 10,
            },
          },
        ],
      },
    ],
  },
};

在包中,要求模板然后返回:

import tenYearsMs from "years-in-ms";

console.log(tenYearsMs); // 315360000000

現(xiàn)代正義

示例顯示了如何構(gòu)建 modernizr。

入口.js

import modenizr from "./modernizr.js";

modernizr.js

const modernizr = require("modernizr");

module.exports = function (options) {
  return new Promise(function (resolve) {
    // It is impossible to throw an error because modernizr causes the process.exit(1)
    modernizr.build(options, function (output) {
      resolve({
        cacheable: true,
        code: `var modernizr; var hadGlobal = 'Modernizr' in window; var oldGlobal = window.Modernizr; ${output} modernizr = window.Modernizr; if (hadGlobal) { window.Modernizr = oldGlobal; } else { delete window.Modernizr; } export default modernizr;`,
      });
    });
  });
};

webpack.config.js

const path = require("path");
module.exports = {
  module: {
    rules: [
      {
        test: path.resolve(__dirname, "src", "modernizr.js"),
        use: [
          {
            loader: "val-loader",
            options: {
              minify: false,
              options: ["setClasses"],
              "feature-detects": [
                "test/css/flexbox",
                "test/es6/promises",
                "test/serviceworker",
              ],
            },
          },
        ],
      },
    ],
  },
};

菲力特

示例顯示了如何構(gòu)建 figlet。

入口.js

import { default as figlet } from "./figlet.js";

console.log(figlet);

figlet.js

const figlet = require("figlet");

function wrapOutput(output, config) {
  let figletOutput = "";

  if (config.textBefore) {
    figletOutput += encodeURI(`${config.textBefore}\n`);
  }

  output.split("\n").forEach((line) => {
    figletOutput += encodeURI(`${line}\n`);
  });

  if (config.textAfter) {
    figletOutput += encodeURI(`${config.textAfter}\n`);
  }

  return `module.exports = decodeURI("${figletOutput}");`;
}

module.exports = function (options) {
  const defaultConfig = {
    fontOptions: {
      font: "ANSI Shadow",
      horizontalLayout: "default",
      kerning: "default",
      verticalLayout: "default",
    },
    text: "FIGLET-LOADER",
    textAfter: null,
    textBefore: null,
  };

  const config = Object.assign({}, defaultConfig, options);

  return new Promise(function (resolve, reject) {
    figlet.text(config.text, config.fontOptions, (error, output) => {
      if (error) {
        return reject(error);
      }

      resolve({
        cacheable: true,
        code: "module.exports = " + wrapOutput(output, config),
      });
    });
  });
};

webpack.config.js

const path = require("path");
module.exports = {
  module: {
    rules: [
      {
        test: path.resolve(__dirname, "src", "figlet.js"),
        use: [
          {
            loader: "val-loader",
            options: {
              text: "FIGLET",
            },
          },
        ],
      },
    ],
  },
};

貢獻

如果還未閱讀捐獻指南,請抽時間進行閱讀。

執(zhí)照

麻省理工學院

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號