I want to keep a JSON document to store some simple data and I want to require this document and use the JSON object in a define() call so I can use it. This is not an async call. I mean it should be for development but I do want to compile the file on build unlike an actual async call from an API, where the content is dynamic.

推荐答案

The easiest way to do this is by using the requirejs json plugin for this, this will allow you to include your file into the build as well.

https://github.com/millermedeiros/requirejs-plugins
Here is an example:

require(['json!someFile.json'], function(data){
  ...
})
// It does not actually need to be a .json extension, this will work to:
require(['json!someFile'], function(data){
  ...
})

If you want to include the file in your r.js build so that it is always optimized in the main/js bootstrap file you have to add it to the include option

You could also use the require js text plugin for this, it's usually used to load template files but you can use it to load .json files as well.

https://github.com/requirejs/text

然后你必须用JSON.parse解析自己的内容

You could also wrap the json in it's own define() so you can just require it traditionally, but that won't work if you are limited to an actual .json file.

An other option is to require the text file trough ajax your self, with jquery or something.

$.get('somefile.json', function(data) {
  // do something with your data
});

Json相关问答推荐

在Go中,当字段可以根据其他字段具有不同的类型时,什么是正确的方法来卸载JSON?

合并二维数组的Jolt表达式

如何在VegaLite中应用Times New Roman,CaliBiri字体

如何用JQ更改空/布尔/数字的 colored颜色 ?

无法从JSON解析ZonedDateTime,但可以使用格式化程序很好地解析

GO KaZaam转换返回意外结果

用于参考的Jolt变换

使用JQ从jsonl文件中删除具有匹配键/值的行

使用 jq 重新格式化 JSON 输出

错误解析错误:意外令牌:在我的 .eslintrc.json 文件中.为什么?

具有 (RegEx) 模式的 json-schema 中的枚举

从 JSON 响应中获取最新版本发布字段

提交后使用 Rails 7 结合 JSON 标签进行标记

在PowerShell中按时间戳过滤JSON

如何对使用转换器的 Grails 服务进行单元测试?

如何一次加载无限滚动中的所有条目以解析python中的HTML

在 JSON 反序列化期间没有为System.String类型定义无参数构造函数

Jackson Scala 模块的小例子?

在视图中将 .Net 对象转换为 JSON 对象

PostgreSQL 中的 JSON 模式验证?