Google Chrome Uncaught SyntaxError: Cannot use import statement outside a module

I exported my Vizhub project and wanted to run it on Chrome and use the developer options to edit it but I keep running into this:

Uncaught SyntaxError: Cannot use import statement outside a module.

I have found many “solutions” but I don’t think they are fixes for my particular problem.

Please help!

Greetings! Here are some details about how the exported code can be run: How to set up Rollup

The main idea is that you can use Rollup to convert the ES6 modules into a single ES5 build, and run that. This is how most front end builds work locally, using some build toolchain centered around a tool like Rollup or Webpack.

If you want to venture into new territory and try Chrome’s native support for ES modules, you can try <script type="module" src="index.js">, but that would not work with dependencies like React and D3 unless you also set up Import Maps to point to ES6 versions of the dependencies in some CDN.

Good luck!

The occurrence of this error can vary depending on whether you’re dealing with JavaScript on the server-side using Node.js or on the client-side within a web browser. The error “Cannot use import statement outside a module” stems from several potential causes, with the appropriate solution hinging on how you incorporate modules or script tags into your code.

Add type="module" inside the script tag

When working with ECMAScript modules and JavaScript module import statements in the browser, you’ll need to explicitly tell the browser that a script is module. To do this, you have to add type=“module” onto any ‹script› tags that point to a JavaScript module. Once you do this you can import that module without issues.

<script type="module" src="./index.js"></script>

If you are working on Node.js or react applications and using import statements instead of require to load the modules, then ensure your package.json has a property “type”: “module” as shown below.

{
  // ...
  "type": "module",
  // ...
}

In this case it’s probably some quirk of what the VizHub runtime environment supports and doesn’t support. It was not set up with support for <script type="module"... in mind. The idea is that you define your code in index.js, then the system will use that.

If there’s a specific reproduction case I’d be happy to take a look and recommend a way forward! If you have a link to a viz that reproduces the issue, please share it. Thanks!