Javascript/网络包 : how to concatenate all json files in directory with a custom loop over files

标签 javascript json node.js reactjs webpack

我正在用 webpack 构建一个 reactJs 包。 我目前正在尝试将 json 文件连接成一个对象以与 i18next 一起使用。我觉得它很简单,我不想使用过于复杂的解决方案。

我的目录结构如下

messages/locale_name/domain_name.json

如何在我的代码中导入常规对象中的所有 json 文件?

到目前为止,我在一开始就很挣扎,因为我发现需要 require('fs") 的建议,但是 webpack 告诉我它无法解析 fs 模块,我已经看到我无法安装它是默认 Node 配置的一部分。

感谢一些帮助。

谢谢!

最佳答案

经过很多 的摸索,实际上很容易。以下是我最终得到的。关键是正确设置 JSON Loader。

安装JSON Loader对于 Webpack

  1. npm install --save-dev json-loader

将 JSON 加载器添加到您的 Webpack 加载器

  1. 这是使用 context 所必需的将文件拉入。
  2. 将此添加到您的 webpack.config.js 加载器 { test:/\.json$/, loader: 'json' },
  3. 决赛可能是这样的:
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$/) );
  1. 其中“modules”是我的 app.js 的子目录(在我的例子中是 ./src/modules)。
  2. 所有 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/

相关文章:

Json 解析 F#

javascript - 在 R 中将 rpart 输出转换为 JSON 格式

javascript - Data.map 不是一个函数

Node.js - 由于 .msi 原因,无法安装它并显示错误

javascript - 使用 JavaScript 进行网页抓取?

javascript - EXTJS 在 Ext.window.Window 中显示 View

javascript - Backbone.js - 必须指定 "url"属性或函数

javascript - 向下滚动页面时,HTML5 Canvas 上的 map 动画沿着路径移动

angularjs - 使用 ng-repeat 如何从嵌套的 JSON 对象中检索数据

node.js - 对 node.js 的 Reactive-Extensions/RxJS 实现