4

I am trying to turn a React Native app into a React Native Web app as well.

I want to do the following kind of import:

if (Platform.OS !== 'web') {
    import { Route, Link, Switch, push, DeepLinking } from "react-router-native";
}

However I get the error:

Syntax error: 'import' and 'export' may only appear at the top level (16:4)

Now I've tried to add an ESLint configuration in my package.json to prevent this:

  "eslintConfig": {
    "parser": "babel-eslint",
    "parserOptions": {
      "sourceType": "module",
      "allowImportExportEverywhere": true
    }
  }

But it is still happening.

How do I allow dynamic imports?

Steven Matthews
  • 9,705
  • 45
  • 126
  • 232
  • 1
    This is not a linting problem but literal code problem. You get a SyntaxError, after all. The error does explain exactly what's wrong - you cannot have `import` in a block, it *has* to be top level. `import`/`export` statements are designed to be statically analysable, so if you *conditionally* want to import something, that requires running logic and thus it cannot be parsed without running the application. – VLAZ Apr 11 '20 at 13:53
  • The dynamic form of `import("somemodule.js")` doesn't work in IE11 but it allows importing modules dynamically. It returns a Promise. – Pointy Apr 11 '20 at 13:59
  • [This related question has an alternative Babel solution.](https://stackoverflow.com/questions/37902849/import-and-export-may-only-appear-at-the-top-level?rq=1) – Pointy Apr 11 '20 at 14:05
  • @Pointy Nothing I'm changing in webpack.config.js or .babelrc seems to be changing the error message – Steven Matthews Apr 11 '20 at 14:27
  • You have to either use the native JavaScript dynamic version, *or* get Babel to do the importing at build time. In your case, I think you'll want the dynamic import because your code apparently wants to make decisions at runtime (in the browser). – Pointy Apr 11 '20 at 14:32
  • @Pointy While I've done a bit of React & React Native work, I'm still learning about babel & webpack etc. What file do I put it into? How would I do the Javascript dynamic version? I've got plugins: ["@babel/plugin-syntax-dynamic-import"], in both my babel.config.js and my webpack.config.js (but not my .babelrc file) – Steven Matthews Apr 11 '20 at 14:48
  • The JavaScript dynamic `import` looks and works like a function call, and it returns a Promise. Thus you can use it with `await` or a `.then()` callback. – Pointy Apr 11 '20 at 15:11

0 Answers0