v14.2.0Linux c89b7c439bd7 4.19.76-linuxkit #1 SMP Fri Apr 3 15:53:26 UTC 2020 x86_64 LinuxCreate docker image that generates package.json and index.js in root of filesystem:
FROM node:14-alpine
RUN echo '{ "type": "module" }' > package.json
RUN echo 'import fs from "fs";' > index.js
CMD ["node", "index.js"]
Build and run the container:
docker build -t app .
docker run --rm app
Output:
(node:1) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
/index.js:1
import fs from "fs";
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (vm.js:344:18)
at wrapSafe (internal/modules/cjs/loader.js:1106:15)
at Module._compile (internal/modules/cjs/loader.js:1140:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1196:10)
at Module.load (internal/modules/cjs/loader.js:1040:32)
at Function.Module._load (internal/modules/cjs/loader.js:929:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
Always.
index.js should be loaded as es module because the nearest package.json has "type": "module" field.
index.js is being loaded as commonjs.
If package.json and index.js are generated in some subdirectory - everything works. You can check it with the following image:
FROM node:14-alpine
# add workdir to generate files in /app not in /
WORKDIR app
RUN echo '{ "type": "module" }' > package.json
RUN echo 'import fs from "fs";' > index.js
CMD ["node", "index.js"]
The reason of such behavior is this line:
(separatorIndex = checkPath.lastIndexOf(path.sep)) > rootSeparatorIndex
When checkPath = '/index.js', both separatorIndex and rootSeparatorIndex are equals to 0 and condition does not pass.
/cc @nodejs/modules-active-members
Yes this looks like a bug to me, we should support a type at the root. PRs to fix welcome, although understood testing might be an issue!
Most helpful comment
Yes this looks like a bug to me, we should support a type at the root. PRs to fix welcome, although understood testing might be an issue!