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
CommonJSstandard
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
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.
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 prunecan clear build cache. After pruning and rebuilding, it worked.

