如何使用requirejs加载静态JSON文件? [英] How do I use requirejs to load a static JSON file?

查看:449
本文介绍了如何使用requirejs加载静态JSON文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想保留一个JSON文档来存储一些简单的数据,并且我需要此文档并在define()调用中使用JSON对象,以便可以使用它.这不是async调用.我的意思是应该用于开发,但是我确实希望在构建时编译文件,这与从API进行的实际async调用不同,后者的内容是动态的.

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.

推荐答案

最简单的方法是为此使用requirejs json插件,这还将使您也可以将文件包括在构建中.

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
这是一个示例:

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){
  ...
})

如果要将文件包含在r.js构建中,以便始终在main/js引导程序文件中对其进行优化,则必须将其添加到include选项

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

您也可以使用require js文本插件,它通常用于加载模板文件,但是您也可以使用它来加载.json文件.

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
(如果需要,请包含 json2.js 以提供对较旧浏览器的支持)

You will have to parse the contents your self then with JSON.parse
(Include json2.js to provide support for older browsers if that's required)

您还可以将json包装在其自己的define()中,这样您就可以按传统要求使用它,但是如果您仅限于实际的.json文件,则无法使用.

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.

另一种选择是通过jquery或其他工具要求文本文件通过ajax.

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
});

这篇关于如何使用requirejs加载静态JSON文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆