简体   繁体   中英

How to load external js file in React?

I have a data.js file with the following structure:

var DATA= {
  "groups": [{
    "id": "1",
    "name": "group 1",
    "subgroups": [{}, {}, ...]
  }, ...],
  ...
}

Is it possible to load this file in my React app and make the DATA var available in any component (I will probably want to initiate Redux state with it), if I can't use export in this file and can't turn it into regular JSON file? Basically I can't edit this file. How can it be achieved?

You can definitely use export in .js file. export default or module.exports should work. If you aren't using a language transformer then use the later approach.

var DATA = {
  "groups": [{
    "id": "1",
    "name": "group 1",
    "subgroups": [{}, {}, ...]
  }, ...],
  ...
}

module.exports = DATA;

Otherwise convert the file into json format and directly use it.

{
  "groups": [{
    "id": "1",
    "name": "group 1",
    "subgroups": [{}, {}, ...]
  }, ...],
  ...
}

React app file.js:

import data from './data.json';

// do something with data.groups

As I understand it, you just have a file with this exact structure and are looking for a way to access it in your app. Since it uses a var declaration, you can just include it in your web app via a <script> tag and DATA variable will be globally available in your code. If you use TypeScript or FlowType, you should also provide a declaration file with declare var DATA: Data; where Data would be your custom interface describing the structure of this data object. What I would suggest instead, though, is creating a single module that will consume the variable, provide a declaration in this module only, transform it however I like and export it from there. Just to give you an idea what it would look like:

interface Data {
    groups: Group[];
}

interface Group {
    id: string;
    name: string;
    subgroups: {}[];  // you might provide more type information here, but to begin it would do as well
}

declare var DATA: Data;

const APP_DATA: Data = DATA;
export default APP_DATA;

Assuming:

  • The data.js file is available during build time
  • File has content in pre-defined format
  • You are using webpack to bundle your application(Optional)

You can use webpack raw-loader (Other bundlers probably have alternatives) to load the content of the file and then parse the content to get the required data.

Example 👇

编辑1o92xyn41q

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM