Skip to content

Commit

Permalink
Try to make the error nicer when mixing ESM and CommonJS
Browse files Browse the repository at this point in the history
We define `module` and `exports` on the global object, so that *if* the
executed code isn't part of CommonJS which defines them, it will access
the global ones.

The global ones just error out on access with a message pointing out
that this likely is due to mixing CommonJS and ESM.
  • Loading branch information
mstoykov committed Jul 9, 2024
1 parent 8c5dd92 commit a78b502
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
13 changes: 13 additions & 0 deletions js/bundle.go
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,19 @@ func (b *Bundle) setInitGlobals(rt *sobek.Runtime, vu *moduleVUImpl, modSys *mod
}
return openImpl(rt, b.filesystems["file"], pwd, filename, args...)
})
warnAboutModuleMixing := func(name string) {
warnFunc := rt.ToValue(func() error {
return fmt.Errorf(
"you are trying to access identifier %q, this likely is due to mixing ESM and CommonJS syntax",
name)
})
err := rt.GlobalObject().DefineAccessorProperty(name, warnFunc, warnFunc, sobek.FLAG_FALSE, sobek.FLAG_FALSE)
if err != nil {
panic(fmt.Errorf("failed to set '%s' global object: %w", name, err))
}
}
warnAboutModuleMixing("module")
warnAboutModuleMixing("exports")
}

func generateFileLoad(b *Bundle) modules.FileLoader {
Expand Down
2 changes: 1 addition & 1 deletion js/module_loading_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ func TestLoadExportsIsntUsableInModule(t *testing.T) {
initVU, err := r.NewVU(ctx, 1, 1, ch)
require.NoError(t, err)
vu := initVU.Activate(&lib.VUActivationParams{RunContext: ctx})
require.ErrorContains(t, vu.RunOnce(), "ReferenceError: exports is not defined")
require.ErrorContains(t, vu.RunOnce(), `you are trying to access identifier "exports"`)
})
}
}
Expand Down

0 comments on commit a78b502

Please sign in to comment.