Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix broken NewExpressions containing require calls #340

Merged
merged 2 commits into from
Aug 21, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions internal/bundler/bundler_default_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,27 @@ func TestNestedCommonJS(t *testing.T) {
})
}

// This test makes sure that NewExpressions containing require() calls aren't
// broken.
func TestNewExpressionCommonJS(t *testing.T) {
default_suite.expectBundled(t, bundled{
files: map[string]string{
"/entry.js": `
new (require("./foo.js")).Foo();
`,
"/foo.js": `
class Foo {}
module.exports = {Foo};
`,
},
entryPaths: []string{"/entry.js"},
options: config.Options{
IsBundling: true,
AbsOutputFile: "/out.js",
},
})
}

func TestCommonJSFromES6(t *testing.T) {
default_suite.expectBundled(t, bundled{
files: map[string]string{
Expand Down
13 changes: 13 additions & 0 deletions internal/bundler/snapshots/snapshots_default.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1203,6 +1203,19 @@ TestNestedScopeBug
a();
})();

================================================================================
TestNewExpressionCommonJS
---------- /out.js ----------
// /foo.js
var require_foo = __commonJS((exports, module) => {
class Foo {
}
module.exports = {Foo};
});

// /entry.js
new (require_foo()).Foo();

================================================================================
TestNodeModules
---------- /Users/user/project/out.js ----------
Expand Down
5 changes: 3 additions & 2 deletions internal/printer/printer.go
Original file line number Diff line number Diff line change
Expand Up @@ -1226,6 +1226,7 @@ const (
forbidCall = 1 << iota
forbidIn
hasNonOptionalChainParent
wrapRequireCall
)

func (p *printer) printUndefined(level ast.L) {
Expand Down Expand Up @@ -1290,7 +1291,7 @@ func (p *printer) printExpr(expr ast.Expr, level ast.L, flags int) {
p.printSpaceBeforeIdentifier()
p.print("new")
p.printSpace()
p.printExpr(e.Target, ast.LNew, forbidCall)
p.printExpr(e.Target, ast.LNew, forbidCall|wrapRequireCall)

// TODO: Omit this while minifying
p.print("(")
Expand Down Expand Up @@ -1363,7 +1364,7 @@ func (p *printer) printExpr(expr ast.Expr, level ast.L, flags int) {
}

case *ast.ERequire:
wrap := level >= ast.LNew
wrap := level >= ast.LNew || (flags&wrapRequireCall) != 0
if wrap {
p.print("(")
}
Expand Down