You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Webpack编译时将生成的JSON文件引入JavaScript?

解决方案:编译时将JSON纳入构建资源

方法1:编写Webpack自定义插件

直接在Webpack编译流程中生成文件列表并将其作为模块注入,无需额外生成JSON文件到dist目录。

  1. 新建插件文件(如FileListPlugin.js):
const fs = require('fs');
const path = require('path');

class FileListPlugin {
  constructor(options) {
    this.targetDir = options.targetDir;
    this.outputModuleName = options.outputModuleName || 'important_files';
  }

  apply(compiler) {
    compiler.hooks.emit.tapAsync('FileListPlugin', (compilation, callback) => {
      const files = fs.readdirSync(path.resolve(__dirname, this.targetDir));
      const fileListJson = JSON.stringify(files);

      // 将文件列表作为模块添加到构建资源中
      compilation.assets[`${this.outputModuleName}.json`] = {
        source: () => fileListJson,
        size: () => fileListJson.length
      };

      callback();
    });
  }
}

module.exports = FileListPlugin;
  1. 在webpack.config.js中配置插件:
const FileListPlugin = require('./FileListPlugin');

module.exports = {
  // 其他Webpack配置...
  plugins: [
    new FileListPlugin({
      targetDir: './path/to/your/target/directory', // 目标文件目录
      outputModuleName: 'important_files'
    })
  ]
};
  1. 在代码中直接引入:
import important_files from 'important_files.json';
console.log(important_files); // 直接获取文件列表数组

此方案会将JSON内容打包进bundle,完全在编译阶段完成处理,无需读取dist目录文件。

方法2:预生成JSON到源码目录

通过Node脚本在Webpack编译前生成JSON文件到源码目录,让Webpack自动将其作为源码资源处理。

  1. 新建生成脚本generate-file-list.js:
const fs = require('fs');
const path = require('path');

const targetDir = './path/to/your/target/directory';
const outputPath = path.resolve(__dirname, 'src/assets/important_files.json');

const files = fs.readdirSync(targetDir);
fs.writeFileSync(outputPath, JSON.stringify(files, null, 2));
  1. 在package.json中添加预编译命令:
{
  "scripts": {
    "prebuild": "node generate-file-list.js",
    "build": "webpack"
  }
}
  1. 在代码中引入:
import important_files from './assets/important_files.json';

此方案操作简单,适合文件列表无需实时动态更新的场景,每次构建前都会重新生成最新的JSON文件。

方法3:用require.context直接获取(无需JSON文件)

如果仅需获取目录文件列表,可直接使用Webpack内置的require.contextAPI,完全跳过JSON文件生成步骤:

// 匹配指定目录下的文件,可自定义后缀规则
const filesContext = require.context('./path/to/target', false, /\.(js|png|svg)$/);
// 提取文件名(去掉开头的'./')
const important_files = filesContext.keys().map(key => key.slice(2));

console.log(important_files); // 得到目标目录的文件列表数组

此方案是最轻量化的实现,直接在编译阶段由Webpack解析目录并生成文件列表。


内容的提问来源于stack exchange,提问作者Newbrict

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 15:40:23