k6 icon indicating copy to clipboard operation
k6 copied to clipboard

ESM discussion: `open` and `require` are relative to?

Open mstoykov opened this issue 2 years ago • 0 comments

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.

mstoykov avatar Sep 01 '22 15:09 mstoykov