Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

javascript - How do I use requirejs to load a static JSON file?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...