使用webpack的require.context无法获取文件内容的问题求助
解决浏览器端批量加载本地文本文件内容的问题
你遇到的问题是webpack默认将txt文件当作资源处理,导出的是文件路径而非内容,需要配置loader让webpack读取文本内容。以下是具体解决步骤:
方法一:配置webpack全局loader
- 安装raw-loader
npm install raw-loader --save-dev
- 修改webpack.config.js,添加txt文件的loader规则
module.exports = { module: { rules: [ { test: /\.txt$/i, use: 'raw-loader', }, ], }, };
- 保持你原来的代码不变,此时
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
相关产品推荐
相关产品推荐

