Import JSON file in React

前端 未结 11 1080
遥遥无期
遥遥无期 2020-11-28 06:05

I\'m new to React and I\'m trying to import a JSON DATA variable from an external file. I\'m getting the following error:

Cannot find mo

11条回答
  •  盖世英雄少女心
    2020-11-28 06:49

    This old chestnut...

    In short, you should be using require and letting node handle the parsing as part of the require call, not outsourcing it to a 3rd party module. You should also be taking care that your configs are bulletproof, which means you should check the returned data carefully.

    But for brevity's sake, consider the following example:

    For Example, let's say I have a config file 'admins.json' in the root of my app containing the following:

    admins.json
    [{
      "userName": "tech1337",
      "passSalted": "xxxxxxxxxxxx"
    }]
    

    Note the quoted keys, "userName", "passSalted"!

    I can do the following and get the data out of the file with ease.

    let admins = require('~/app/admins.json');
    console.log(admins[0].userName);
    

    Now the data is in and can be used as a regular (or array of) object.

提交回复
热议问题