Home > Back-end >  Stackblitz: Cannot use import statement outside a module
Stackblitz: Cannot use import statement outside a module

Time:12-09

Using stackblitz even if I create simplest demo for this library I get this error:

Cannot use import statement outside a module

I found related question from here, but it doesn't help:

  • I can't edit package.json because I think they suggest to edit package.json of module which I imported
  • Another suggestion is to edit script tag, but on stackblitz environment, I can't find it either, it just shows the index.html file

here is demo:

import React from 'react';
import { FaBeer } from 'react-icons/fa';
class Question extends React.Component {
  render() {
    return (
      <h3>
        {' '}
        Lets go for a <FaBeer />?{' '}
      </h3>
    );
  }
}

Can someone help?

CodePudding user response:

You need to configure your local tsconfig like in this example

{
  "compilerOptions": {
    "module": "esnext",
    "noImplicitAny": true,
    "removeComments": true,
    "preserveConstEnums": true,
    "esModuleInterop": true,
    "sourceMap": true,
    "lib": ["es6", "dom", "es2017"]
  }
}

in this approach, we are just specifying esnext module types instead of commonjs, and turning on esModuleInterop (needed for react itself)

I do notice that with some frequency when reopening this example in firefox, often I get an error:


Error in /~/question.tsx (24:21)
import declarations may only appear at top level of a module

but opening/reopening in chrome has not produced this issue. Simply modifying the tsconfig.json file in any way, saving, then undoing and saving again causes it to then load correctly in firefox. This leads me to believe that @StackBlitz has a configuration issue related to some non-chrome browsers, it is not an issue with the code.

CodePudding user response:

Inside package.json add

{
"type":"module"
}
  • Related