1

This is what I mean:

import React from "react";

class App extends React.Component {
   constructor(props) {
      super(props);
      this.state = { data: [] }
   }

   componentWillMount() {
      this.setState({ data: import "./data/myData.json" });
   }

   // etc...
}

This does not work. But this does:

import React from "react";

class App extends React.Component {
   constructor(props) {
      super(props);
      this.state = { data: [] }
   }

   componentWillMount() {
      this.setState({ data: require("./data/myData.json") });
   }

   // etc...
}

The only reason I want to get it working with ES6 syntax is to be consistent. Is this achievable?

jsdev17
  • 1,050
  • 2
  • 15
  • 25
  • Possible duplicate of [How to import a json file in ecmascript 6?](https://stackoverflow.com/questions/34944099/how-to-import-a-json-file-in-ecmascript-6) – Herohtar Sep 12 '18 at 18:07
  • Possible duplicate of [Using Node.js require vs. ES6 import/export](https://stackoverflow.com/questions/31354559/using-node-js-require-vs-es6-import-export) – Sunny Patel Sep 12 '18 at 18:07
  • 2
    `import` is not a drop-in replacement for `require`. Notably, `import` statements are statically analyzed, so you can't use conditional loading or defer loading this way. Put `import` statements at the top of the file, and if you want to conditionally load something, read the file using normal tools (`fetch` or XHR requests on the web). – coreyward Sep 12 '18 at 18:10

0 Answers0