From 1ced365af577357e644272d7a87e6103e1b5608e Mon Sep 17 00:00:00 2001 From: icexin Date: Sun, 8 Mar 2020 11:39:09 +0800 Subject: [PATCH] fix module double load --- module.go | 2 +- motto_test.go | 24 +++++++++++++++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/module.go b/module.go index ab61d83..8794760 100644 --- a/module.go +++ b/module.go @@ -26,7 +26,7 @@ func CreateLoaderFromSource(source, filename string) ModuleLoader { pwd := filepath.Dir(filename) return func(vm *Motto) (otto.Value, error) { // Wraps the source to create a module environment - source = "(function(module) {var require = module.require;var exports = module.exports;var __dirname = module.__dirname;" + source + "\n})" + source := "(function(module) {var require = module.require;var exports = module.exports;var __dirname = module.__dirname;" + source + "\n})" // Provide the "require" method in the module scope. jsRequire := func(call otto.FunctionCall) otto.Value { diff --git a/motto_test.go b/motto_test.go index 05e6ad9..7b980de 100644 --- a/motto_test.go +++ b/motto_test.go @@ -5,9 +5,10 @@ package motto import ( - "github.com/robertkrimen/otto" "io/ioutil" "testing" + + "github.com/robertkrimen/otto" ) func TestModule(t *testing.T) { @@ -66,3 +67,24 @@ func fsModuleLoader(vm *Motto) (otto.Value, error) { return vm.ToValue(fs) } + +func TestDoubleLoadModule(t *testing.T) { + loader := CreateLoaderFromSource(`{ + module.exports = "bar"; + }`, "") + + testLoad := func() { + vm := New() + vm.AddModule("foo", loader) + v, err := vm.Require("foo", ".") + if err != nil { + t.Fatal(err) + } + s, _ := v.ToString() + if s != "bar" { + t.Errorf("expect bar, got %s", s) + } + } + testLoad() + testLoad() +}