Skip to content

[ES modules] package.json located in root path can't be resolved when checking type field #33438

Closed
@vitalets

Description

@vitalets
  • Version: v14.2.0
  • Platform: Linux c89b7c439bd7 4.19.76-linuxkit #1 SMP Fri Apr 3 15:53:26 UTC 2020 x86_64 Linux

What steps will reproduce the bug?

Create 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

How often does it reproduce? Is there a required condition?

Always.

What is the expected behavior?

index.js should be loaded as es module because the nearest package.json has "type": "module" field.

What do you see instead?

index.js is being loaded as commonjs.

Additional information

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    confirmed-bugIssues with confirmed bugs.esmIssues and PRs related to the ECMAScript Modules implementation.moduleIssues and PRs related to the module subsystem.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions