syntaxerror: cannot use import statement outside module – Code Example


Here is the solution for syntaxerror: cannot use import statement outside a module

1. Add this to package.json

  "type": "module"

2. Or, use type=module in <script> tag –

<script type="module" src="/path/to/js/file.js"></script>

Other issues you may face

1. ReferenceError: require is not defined

It means you will need to convert all require() syntax with import syntax.

- const module = require('/path/to/module.js')
+ import module from '/path/to/module.js'

2. Stuck in infinite loop

If you are stuck in infinite loop then replace require() with import() function rather than import statement –

import("/path/to/module.js").then(modu => { module = modu });

3. Loading module from wrong directory

Check if you are loading module from src directory or build directory. For production your external JS needs to be in build directory.

4. Uncaught ReferenceError: … is not defined

It means that you are using a variable from outside which is scoped within module. This variable is no globally scoped and hence you can’t use it as window.your_variable.