Skip to content

ESM discussion: open and require are relative to? #2674

@mstoykov

Description

@mstoykov

Background:

Currently, require and open are both relative to the current root module/script that is being executed. This is best explain with an example:

If you have.

main.js that imports 'folder/B.js'

// this is main.js
import { a } from "./folder/B.js";
var somefile = a(); // this will open `./data.json`
export default() {}
export function a () {
   return open("./data.json");
}
a() // this will open `./folder/data.json`

The same goes for require.

Problem/question:

import() (the dynamic import) is defined as being relative to the file it's being written in as in the above case if you replace open with import it will in both instances open ./folder/data.json.

The same is technically true for how require is defined :( , from https://wiki.commonjs.org/wiki/Website:Index/specs/modules/1.0

Relative identifiers are resolved relative to the identifier of the module in which "require" is written and called.

Arguably both require and open will be almost always be used in the top context of the module/script, so it wouldn't matter - they will just always be relative to the file they are written in.

So the questions are two:

  1. should require be fixed to be relative to the module it is in ... basically the same as import() and as it's described?
  2. should open be the same just to not be confusing?

From implementation perspective making it all the same will be way easier in ESM as getting the root module/script that is currently running isn't a thing goja currently supports and likely will require some hacks.

Metadata

Metadata

Assignees

Labels

evaluation neededproposal needs to be validated or tested before fully implementing it in k6question

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions