requirejs 加载静态 JSON 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15314019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
requirejs load static JSON file
提问by ThomasReggi
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 a "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.
我想保留一个 json 文档来存储一些简单的数据,我想需要这个文档并在define()调用中使用 json 对象,以便我可以使用它。这不是“异步”调用。我的意思是它应该用于开发,但我确实想在构建时编译文件,这与来自 API 的实际异步调用不同,其中内容是动态的。
回答by Willem D'Haeseleer
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.
最简单的方法是为此使用 requirejs json 插件,这将允许您将文件也包含到构建中。
https://github.com/millermedeiros/requirejs-plugins
Here is an example:
https://github.com/millermedeiros/requirejs-plugins
这是一个例子:
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
如果您想在 r.js 构建中包含该文件,以便它始终在 main/js 引导文件中进行优化,则必须将其添加到 include 选项中
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.
您也可以为此使用 require js 文本插件,它通常用于加载模板文件,但您也可以使用它来加载 .json 文件。
https://github.com/requirejs/text
https://github.com/requirejs/text
You will have to parse the contents your self then with JSON.parse
(Include json2.jsto provide support for older browsers if that's required)
你将不得不解析你自己的内容JSON.parse
(如果需要,包括json2.js以提供对旧浏览器的支持)
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 .jsonfile.
您也可以将 json 包装在它自己的 define() 中,这样您就可以传统地要求它,但如果您仅限于实际.json文件,那将不起作用。
An other option is to require the text file trough ajax your self, with jquery or something.
另一种选择是使用 jquery 或其他东西通过 ajax 要求文本文件。
$.get('somefile.json', function(data) {
// do something with your data
});
回答by mikemaccana
Posting this an an answer, because:
发布这个答案,因为:
- it's what the user asking the question actually used as their solution
- it's cleaner to look at than require text, since it always does the JSON.parse() for you.
- 这是提出问题的用户实际用作他们的解决方案的内容
- 看起来比需要文本更清晰,因为它总是为你做 JSON.parse() 。
RequireJS has a JSON plugin. The syntax is simply:
RequireJS 有一个 JSON 插件。语法很简单:
require(['json!someData.json'], function(data){
...
})

