Load static JSON file in Webpack Load static JSON file in Webpack angularjs angularjs

Load static JSON file in Webpack


You're using fetch to request a JSON file and that will only happen at runtime. Furthermore, webpack only processes anything that is imported. You expected it to handle an argument to a function, but if webpack did that, every argument to a function would be considered a module and that breaks any other use for that function.

If you want your loaders to kick in, you can import the file.

import './portal/content/json/menu.json';

You can also import the JSON and use it directly instead of fetching it a runtime. Webpack 2 uses json-loader by default for all .json files. You should remove the .json rule and you would import the JSON as follows.

import menu from './portal/content/json/menu.json';

menu is the same JavaScript object that you would get from your getMenu function.


if you'd like your json to be loaded in runtime/deferred you can use awesome webpack's dynamic imports feature:

import(    /* webpackChunkName: "json_menu" */    './portal/content/json/menu.json');

it will return a Promise which resolves to the module object, with "default" field containing your data. So you might want something like this (with es6 it looks really nice):

import(    /* webpackChunkName: "json_menu" */    './portal/content/json/menu.json').then(({default: jsonMenu}) => {    // do whatever you like with your "jsonMenu" variable    console.log('my menu: ', jsonMenu);});

Notice that dynamic imports require a babel plugin syntax-dynamic-import, install it with npm:

npm i babel-plugin-syntax-dynamic-import -D

Have a nice day