我如何在 Webpack 构建期间评估 Node 脚本并使其内容可用于编译代码?

How can I evaluate a Node script during a Webpack build and make it contents available to the compiled code?

我有一个 Node 脚本,它多次使用 fs.readFileSync 来读取文件系统中存在的各种 JSON5 配置文件。根据 ENV 变量中的某些标准,这些被读入、组合、操纵、附加等。此文件的输出是一个 JavaScript 对象,通过 module.exports.

我希望每次 运行 我的 Webpack 构建过程和捆绑包中可用的输出 JS 对象时都对这个脚本进行评估,所以当我的客户端 React 脚本执行 import { foo, bar } from 'config'; 时,那些客户端代码可以访问这些值。

这似乎是加载器可以解决的问题,但我无法让它们中的任何一个工作。

如何在 Webpack 编译期间评估 Node 脚本并使其导出可用于编译的客户端代码?

正如我在对你的问题的评论中所说,在 webpack 中处理配置的惯用方法是 DefinePlugin,所以在你的情况下,这意味着在你的 webpack 配置中进行配置处理。然后 Webpack 会自动就地处理配置变量的插值,你不需要使用 import 语句引入配置。类似于:

// webpack.config.js
const webpack = require("webpack");
const config = require("./process-config")

module.exports = {
  // ...
  plugins: [
    webpack.DefinePlugin({
      config
    })
  ]
};
// app.js
if (config.SOME_CONFIG_VAR) {
  // do work when SOME_CONFIG_VAR=true
}

话虽如此,另一种更符合您正在寻找的方法可能是使用 val-loader 这是一个加载器

executes a given module, and returns the result of the execution at build-time, when the module is required in the bundle

[source]

使用 val-loader 可能类似于:

// webpack.config.js
module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /config.js$/,
        use: [{ loader: "val-loader" }]
      }
    ]
  }
}
// config.js
const config = require("./process-config.js");
const JSON = require("json5");

module.exports = {
  code: `module.exports = "${JSON.stringify(config)}"`
}
// app.js
const config = require("./config.js");

if (config.SOME_CONFIG_VAR) {
  // do work when SOME_CONFIG_VAR is truthy
}