Skip to content

Commit

Permalink
fix: make require to work without setting global module, exports
Browse files Browse the repository at this point in the history
  • Loading branch information
mstoykov committed Aug 7, 2019
1 parent 21cf0c9 commit ebc684c
Showing 1 changed file with 9 additions and 10 deletions.
19 changes: 9 additions & 10 deletions js/initcontext.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,17 +138,10 @@ func (i *InitContext) requireFile(name string) (goja.Value, error) {
if !ok || pgm.module == nil {
i.pwd = loader.Dir(fileURL)
defer func() { i.pwd = pwd }()

// Swap the importing scope's exports out, then put it back again.
oldExports := i.runtime.Get("exports")
defer i.runtime.Set("exports", oldExports)
oldModule := i.runtime.Get("module")
defer i.runtime.Set("module", oldModule)
exports := i.runtime.NewObject()
i.runtime.Set("exports", exports)
pgm.module = i.runtime.NewObject()
_ = pgm.module.Set("exports", exports)
i.runtime.Set("module", pgm.module)

if pgm.pgm == nil {
// Load the sources; the loader takes care of remote loading, etc.
data, err := loader.Load(i.filesystems, fileURL, name)
Expand All @@ -168,17 +161,23 @@ func (i *InitContext) requireFile(name string) (goja.Value, error) {
i.programs[fileURL.String()] = pgm

// Run the program.
if _, err := i.runtime.RunProgram(pgm.pgm); err != nil {
f, err := i.runtime.RunProgram(pgm.pgm)
if err != nil {
delete(i.programs, fileURL.String())
return goja.Undefined(), err
}
if call, ok := goja.AssertFunction(f); ok {
if _, err = call(exports, pgm.module, exports); err != nil {
return nil, err
}
}
}

return pgm.module.Get("exports"), nil
}

func (i *InitContext) compileImport(src, filename string) (*goja.Program, error) {
pgm, _, err := i.compiler.Compile(src, filename, "(function(){\n", "\n})()\n", true)
pgm, _, err := i.compiler.Compile(src, filename, "(function(module, exports){\n", "\n})\n", true)
return pgm, err
}

Expand Down

0 comments on commit ebc684c

Please sign in to comment.