Skip to content

Commit

Permalink
map to "null" instead of "0" to fix "cjs-module-lexer"
Browse files Browse the repository at this point in the history
  • Loading branch information
evanw committed Mar 12, 2021
1 parent d64d819 commit 0e6a9b2
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 11 deletions.
15 changes: 8 additions & 7 deletions internal/bundler/linker.go
Original file line number Diff line number Diff line change
Expand Up @@ -1852,7 +1852,7 @@ func (c *linkerContext) createExportsForFile(sourceIndex uint32) {
)
}

// "{a, b, if: 0}"
// "{a, b, if: null}"
var moduleExports []js_ast.Property
for _, export := range repr.meta.sortedAndFilteredExportAliases {
if export == "default" {
Expand All @@ -1861,13 +1861,14 @@ func (c *linkerContext) createExportsForFile(sourceIndex uint32) {
continue
}

// "{if: 0}"
// "{if: null}"
var value *js_ast.Expr
if _, ok := js_lexer.Keywords[export]; ok {
// Make sure keywords don't cause a syntax error. Note that this is not
// currently supported by the "cjs-module-lexer" library, but this appears
// to be a bug: https://github.com/guybedford/cjs-module-lexer/issues/47.
value = &js_ast.Expr{Data: &js_ast.ENumber{Value: 0}}
// Make sure keywords don't cause a syntax error. This has to map to
// "null" instead of something shorter like "0" because the library
// "cjs-module-lexer" only supports identifiers in this position, and
// it thinks "null" is an identifier.
value = &js_ast.Expr{Data: &js_ast.ENull{}}
}

moduleExports = append(moduleExports, js_ast.Property{
Expand All @@ -1876,7 +1877,7 @@ func (c *linkerContext) createExportsForFile(sourceIndex uint32) {
})
}

// "0 && (module.exports = {a, b, if: 0});"
// "0 && (module.exports = {a, b, if: null});"
expr := js_ast.Expr{Data: &js_ast.EBinary{
Op: js_ast.BinOpLogicalAnd,
Left: js_ast.Expr{Data: &js_ast.ENumber{Value: 0}},
Expand Down
9 changes: 5 additions & 4 deletions scripts/end-to-end-tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -899,10 +899,11 @@
exports.async = async () => {
let out = await import('./out.cjs')
let keys = Object.keys(out)
// This doesn't test for "if" because "cjs-module-lexer" currently doesn't parse it
if (!keys.includes('default') || !keys.includes('foo')) throw 'fail'
if (out.foo !== 123 || out.default.foo !== 123 || out.default.if !== 234 || out.default.default !== 345) throw 'fail'
if (
!keys.includes('default') || !keys.includes('foo') || !keys.includes('if') ||
out.foo !== 123 || out.if !== 234 ||
out.default.foo !== 123 || out.default.if !== 234 || out.default.default !== 345
) throw 'fail'
}
`,
}, { async: true }),
Expand Down

0 comments on commit 0e6a9b2

Please sign in to comment.