The error "SyntaxError: Cannot use import statement outside a module" typically occurs when you're trying to use the modern import syntax in a JavaScript environment that doesn't support it natively. This issue is common when working with older versions of Node.js, certain browsers, or a non-module environment. Here's how you can fix this error.

1. Ensure You're Using Modules

First, you need to make sure that the file where you're using the import statement is treated as a module. In Node.js, this can be done by adding "type": "module" in your package.json file. This tells Node.js to treat all .js files as ECMAScript modules (ESM). Here's how you add it:

{
  "name": "your-project",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "start": "node index.js"
  }
}

If you're working with a specific file, you can also change the file extension to .mjs (e.g., index.mjs) to explicitly tell Node.js to treat it as a module.

2. Use a Bundler for Browsers

If you're working in a browser environment, some browsers may not fully support import statements in certain contexts. In such cases, it's better to use a bundler like Webpack or Rollup. These tools allow you to write modern JavaScript using import and export statements, but they bundle everything into a single file that the browser can understand.

For example, with Webpack, you can set up a configuration file (webpack.config.js) and run the bundling process to convert your module-based code into a browser-compatible format.

3. Switch to require() in Node.js

If you're working in a Node.js environment that doesn't support ES modules, you can revert to using the CommonJS require() syntax instead of import. Here's an example:

Instead of:

import express from 'express';

Use:

const express = require('express');

This method works in older versions of Node.js that don't support ES modules.

4. Check Your Environment

Make sure that your development environment or tools (like Node.js or browsers) are up-to-date. Modern JavaScript environments have built-in support for ES modules, but older versions may not. Upgrading Node.js or ensuring you’re using a modern browser can also fix this issue.

By following these steps, you should be able to resolve the "SyntaxError: Cannot use import statement outside a module" and continue using the import statement effectively in your JavaScript project.

Simon

102 Articles

I love talking about tech.