From 923843d7ebe71d19f3d1cb70c0ae61463cf6348f Mon Sep 17 00:00:00 2001 From: Mihail Stoykov Date: Tue, 9 Jul 2024 17:01:20 +0300 Subject: [PATCH] Try to make the error nicer when mixing ESM and CommonJS 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. --- js/bundle.go | 14 ++++++++++++++ js/module_loading_test.go | 2 +- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/js/bundle.go b/js/bundle.go index 43ebdf4d14aa..cbbddf94d378 100644 --- a/js/bundle.go +++ b/js/bundle.go @@ -436,6 +436,20 @@ 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."+ + "This isn't supported in the JavaScript standard, please use only one or the other", + 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 { diff --git a/js/module_loading_test.go b/js/module_loading_test.go index d1d9ef879ddc..863a22935e53 100644 --- a/js/module_loading_test.go +++ b/js/module_loading_test.go @@ -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"`) }) } }