我正在用 webpack 构建一个 reactJs 包。 我目前正在尝试将 json 文件连接成一个对象以与 i18next 一起使用。我觉得它很简单,我不想使用过于复杂的解决方案。
我的目录结构如下
messages/locale_name/domain_name.json
如何在我的代码中导入常规对象中的所有 json 文件?
到目前为止,我在一开始就很挣扎,因为我发现需要 require('fs") 的建议,但是 webpack 告诉我它无法解析 fs 模块,我已经看到我无法安装它是默认 Node 配置的一部分。
感谢一些帮助。
谢谢!
最佳答案
经过很多 的摸索,实际上很容易。以下是我最终得到的。关键是正确设置 JSON Loader。
安装JSON Loader对于 Webpack
npm install --save-dev json-loader
将 JSON 加载器添加到您的 Webpack 加载器
- 这是使用 context 所必需的将文件拉入。
- 将此添加到您的 webpack.config.js 加载器
{ test:/\.json$/, loader: 'json' },
- 决赛可能是这样的:
module.exports = { entry: './src/app.js', output: { path: __dirname, filename: './build/bundle.js' }, module: { loaders: [ { test: /\.json$/, loader: 'json' } ] } }
使用 Context加载文件并将它们保存到数组中
在我的 app.js 中:
function requireAll( requireContext ) {
return requireContext.keys().map( requireContext );
}
var modules = requireAll( require.context("./modules", false, /.json$/) );
- 其中“modules”是我的 app.js 的子目录(在我的例子中是 ./src/modules)。
- 所有 JSON 文件都将加载到数组
[Object, Object, Object]
中,我将其存储到var modules
关于Javascript/网络包 : how to concatenate all json files in directory with a custom loop over files,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37072839/