Cannot use import statement outside a module

Oct 29, 2022 · 1 min read · 142 Words · -Views -Comments

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