Cannot use import statement outside a module

This post explains the ‘Cannot use import statement outside a module’ error, including causes, investigation, and fixes that help resolve build failures efficiently.

Oct 29, 2022 · 1 min read · 142 Words · -Views -Comments · Programming
Node.js 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

Recently, while building a Node project in Docker locally, I got this error: Cannot use import statement outside a module","event":"uncaughtException". After troubleshooting, I noted the fix here.

Environment

  • NodeJS version v12
  • The project uses the CommonJS standard

Meaning of the error

The error stack pointed to node_modules/axios/lib/core/buildFullPath.js. In local development the file looked fine, but inside the Docker container it used ES import syntax. That confirmed the root cause.

Root cause

  1. During Docker builds, package.lock and Node versions should be fixed, so it should match the dev environment. The mismatch implies Docker build caching issues.

  2. History showed I previously installed axios@latest (v1) because I did not pin a version. The v1 package is ES module based. So the likely cause is Docker using a cached build layer. I found docker builder prune can clear build cache. After pruning and rebuilding, it worked.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover