Loading local JSON file

前端 未结 23 2184
悲哀的现实
悲哀的现实 2020-11-22 01:28

I\'m trying to load a local JSON file but it won\'t work. Here is my JavaScript code (using jQuery):

var json = $.getJSON("test.json");
var data = e         


        
23条回答
  •  [愿得一人]
    2020-11-22 01:39

    I'm surprised import from es6 has not been mentioned (use with small files)

    Ex: import test from './test.json'

    webpack 2< uses the json-loader as default for .json files.

    https://webpack.js.org/guides/migrating/#json-loader-is-not-required-anymore

    For TypeScript:

    import test from 'json-loader!./test.json';
    

    TS2307 (TS) Cannot find module 'json-loader!./suburbs.json'

    To get it working I had to declare the module first. I hope this will save a few hours for someone.

    declare module "json-loader!*" {
      let json: any;
      export default json;
    }
    
    ...
    
    import test from 'json-loader!./test.json';
    

    If I tried to omit loader from json-loader I got the following error from webpack:

    BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders. You need to specify 'json-loader' instead of 'json', see https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed

提交回复
热议问题