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

使用webpack的require.context无法获取文件内容的问题求助

解决浏览器端批量加载本地文本文件内容的问题

你遇到的问题是webpack默认将txt文件当作资源处理,导出的是文件路径而非内容,需要配置loader让webpack读取文本内容。以下是具体解决步骤:

方法一:配置webpack全局loader

  1. 安装raw-loader
npm install raw-loader --save-dev
  1. 修改webpack.config.js,添加txt文件的loader规则
module.exports = {
  module: {
    rules: [
      {
        test: /\.txt$/i,
        use: 'raw-loader',
      },
    ],
  },
};
  1. 保持你原来的代码不变,此时files(key)会直接返回文本内容:
const files = require.context('./my-directory', true, /\.txt$/);
files.keys().forEach((key) => {
  const fileContent = files(key);
  // 现在可以直接使用fileContent了
});

方法二:使用inline loader(无需修改webpack配置)

如果你的项目是脚手架生成的(比如vue-cli、create-react-app),不想修改全局webpack配置,可以在require.context里指定loader:

// 给目录路径加上raw-loader!前缀
const files = require.context('raw-loader!./my-directory', true, /\.txt$/);
files.keys().forEach((key) => {
  // 移除key开头的raw-loader!前缀
  const filePath = key.replace(/^raw-loader!/, '');
  const fileContent = files(key);
  // 使用filePath和fileContent
});

原理说明

webpack默认对未配置loader的文件会按资源文件处理,导出的是文件打包后的访问路径。raw-loader的作用是读取文件的原始文本内容,并将其作为模块导出,这样你就能直接获取到文本内容了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 09:42:06