Import JSON file in React

前端 未结 11 1005
遥遥无期
遥遥无期 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 07:01

    With json-loader installed, you can use

    import customData from '../customData.json';
    

    or also, even more simply

    import customData from '../customData';
    

    To install json-loader

    npm install --save-dev json-loader
    
    0 讨论(0)
  • 2020-11-28 07:01

    Simplest approach is following

    // Save this as someJson.js
    const someJson = {
      name: 'Name',
      age: 20
    }
    
    export default someJson
    

    then

    import someJson from './someJson'
    
    0 讨论(0)
  • 2020-11-28 07:02

    Please store your JSON file with the .js extension and make sure that your JSON should be in same directory.

    0 讨论(0)
  • 2020-11-28 07:04

    there are multiple ways to do this without using any third-party code or libraries (the recommended way).

    1st STATIC WAY: create a .json file then import it in your react component example

    my file name is "example.json"

    {"example" : "my text"}
    

    the example key inside the example.json can be anything just keep in mind to use double quotes to prevent future issues.

    How to import in react component

    import myJson from "jsonlocation";
    

    and you can use it anywhere like this

    myJson.example
    

    now there are a few things to consider. With this method, you are forced to declare your import at the top of the page and cannot dynamically import anything.

    Now, what about if we want to dynamically import the JSON data? example a multi-language support website?

    2 DYNAMIC WAY

    1st declare your JSON file exactly like my example above

    but this time we are importing the data differently.

    let language = require('./en.json');
    

    this can access the same way.

    but wait where is the dynamic load?

    here is how to load the JSON dynamically

    let language = require(`./${variable}.json`);
    

    now make sure all your JSON files are within the same directory

    here you can use the JSON the same way as the first example

    myJson.example
    

    what changed? the way we import because it is the only thing we really need.

    I hope this helps.

    0 讨论(0)
  • 2020-11-28 07:06

    One nice way (without adding a fake .js extension which is for code not for data and configs) is to use json-loader module. If you have used create-react-app to scaffold your project, the module is already included, you just need to import your json:

    import Profile from './components/profile';
    

    This answer explains more.

    0 讨论(0)
提交回复
热议问题