Home > other >  Javascript - Load the content of a JSon file with RequireJS
Javascript - Load the content of a JSon file with RequireJS

Time:12-08

I am trying to load a simple JSon file into a variable and I am running into walls.

Here is the code I use :

<html> 
  <head> 
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> 
    <title>Require test</title> 
    <script charset="utf-8" src="require.js"></script>
  </head> 
  <body> 
    <script type="text/javascript"> 
      root = require('./data_test_v2.json');
      console.log(root);
    </script> 
  </body> 
</html>

And this is the error I get :

Uncaught Error: Module name "data_test_v2.json" has not been loaded yet for context: _. Use require([])
https://requirejs.org/docs/errors.html#notloaded

The require.js file is the latest version of RequireJS (from https://requirejs.org/docs/release/2.3.6/comments/require.js).

Seems like a very basic problem.. any help is welcome.

CodePudding user response:

The require function provided by Node.js will load CommonJS modules and JSON.

The require function provided by Require.js will load AMD modules.

They are not designed to be compatible. They have completely different APIs. Require.js does not support loading JSON.


If you want to load data from JSON with client-side code in the browser then use fetch, XHTMLHttpRequest or a library wrapped around one of them (such as axios).

CodePudding user response:

You can use RequireJS to load JSON files, but you will need a JSON plugin for that.

Also, you have to slightly amend your code, as RequireJS is async. It requires you to provide an array of required dependencies to load as the first argument and a callback as a second one. The callback will be executed and the loaded dependencies will be injected as parameters.

<html> 
  <head> 
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> 
    <title>Require test</title> 
    <script charset="utf-8" src="require.js"></script>
  </head> 
  <body> 
    <script type="text/javascript"> 
      root = require(['./data_test_v2.json'], (json) => { console.log(json); });
      console.log(root);
    </script> 
  </body> 
</html>
  • Related