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

Include new URL("...", import.meta.url) references in the import graph. #2470

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
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
5 changes: 5 additions & 0 deletions internal/js_ast/js_ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,7 @@ func (*EIf) isExpr() {}
func (*ERequireString) isExpr() {}
func (*ERequireResolveString) isExpr() {}
func (*EImportString) isExpr() {}
func (*ERelativeURL) isExpr() {}
func (*EImportCall) isExpr() {}

type EArray struct {
Expand Down Expand Up @@ -734,6 +735,10 @@ type ERequireResolveString struct {
ImportRecordIndex uint32
}

type ERelativeURL struct {
ImportRecordIndex uint32
}

type EImportString struct {
// Comments inside "import()" expressions have special meaning for Webpack.
// Preserving comments inside these expressions makes it possible to use
Expand Down
57 changes: 45 additions & 12 deletions internal/js_parser/js_parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -14359,24 +14359,57 @@ func (p *parser) visitExprInOut(expr js_ast.Expr, in exprIn) (js_ast.Expr, exprO

case *js_ast.ENew:
hasSpread := false
isImportGraphURL := false

e.Target = p.visitExpr(e.Target)
p.warnAboutImportNamespaceCall(e.Target, exprKindNew)

for i, arg := range e.Args {
arg = p.visitExpr(arg)
if _, ok := arg.Data.(*js_ast.ESpread); ok {
hasSpread = true
// Test for `new URL("./relative/path.js", import.meta.url)` (https://github.com/evanw/esbuild/issues/795)
if id, ok := e.Target.Data.(*js_ast.EIdentifier); ok {
symbol := p.symbols[id.Ref.InnerIndex]
if symbol.OriginalName == "URL" && len(e.Args) == 2 {
if s, ok := e.Args[0].Data.(*js_ast.EString); ok {
if eDot, ok := e.Args[1].Data.(*js_ast.EDot); ok {
if _, ok := eDot.Target.Data.(*js_ast.EImportMeta); ok {
if eDot.Name == "url" {
// TODO: This should:
// - Include more file types.
// - Understand the relative JS and TS files even if the file extension is not provided (like in TypeScript).
// - Check if the actual file exists in the import graph?
isInImportGraph := strings.HasSuffix(helpers.UTF16ToString(s.Value), ".js") || strings.HasSuffix(helpers.UTF16ToString(s.Value), ".ts")

if isInImportGraph {
isImportGraphURL = true
}
}
}
}
}
}
e.Args[i] = arg
}
if isImportGraphURL {
s, _ := e.Args[0].Data.(*js_ast.EString)
importRecordIndex := p.addImportRecord(ast.ImportDynamic, e.Args[0].Loc, helpers.UTF16ToString(s.Value), nil)
p.importRecordsForCurrentPart = append(p.importRecordsForCurrentPart, importRecordIndex)
e.Args[0] = js_ast.Expr{Loc: e.Args[0].Loc, Data: &js_ast.ERelativeURL{
ImportRecordIndex: importRecordIndex,
}}
} else {
p.warnAboutImportNamespaceCall(e.Target, exprKindNew)

// "new foo(1, ...[2, 3], 4)" => "new foo(1, 2, 3, 4)"
if p.options.minifySyntax && hasSpread && in.assignTarget == js_ast.AssignTargetNone {
e.Args = inlineSpreadsOfArrayLiterals(e.Args)
}
for i, arg := range e.Args {
arg = p.visitExpr(arg)
if _, ok := arg.Data.(*js_ast.ESpread); ok {
hasSpread = true
}
e.Args[i] = arg
}

p.maybeMarkKnownGlobalConstructorAsPure(e)
// "new foo(1, ...[2, 3], 4)" => "new foo(1, 2, 3, 4)"
if p.options.minifySyntax && hasSpread && in.assignTarget == js_ast.AssignTargetNone {
e.Args = inlineSpreadsOfArrayLiterals(e.Args)
}

p.maybeMarkKnownGlobalConstructorAsPure(e)
}

case *js_ast.EArrow:
asyncArrowNeedsToBeLowered := e.IsAsync && p.options.unsupportedJSFeatures.Has(compat.AsyncAwait)
Expand Down
7 changes: 7 additions & 0 deletions internal/js_printer/js_printer.go
Original file line number Diff line number Diff line change
Expand Up @@ -1894,6 +1894,13 @@ func (p *printer) printExpr(expr js_ast.Expr, level js_ast.L, flags printExprFla
p.addSourceMapping(expr.Loc)
p.printRequireOrImportExpr(e.ImportRecordIndex, leadingInteriorComments, level, flags)

case *js_ast.ERelativeURL:
record := &p.importRecords[e.ImportRecordIndex]
if record.Kind == ast.ImportDynamic {
p.addSourceMapping(record.Range.Loc)
p.printQuotedUTF8(record.Path.Text, true /* allowBacktick */)
}

case *js_ast.EImportCall:
var leadingInteriorComments []js_ast.Comment
if !p.options.MinifyWhitespace {
Expand Down
44 changes: 44 additions & 0 deletions scripts/js-api-tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -1450,6 +1450,50 @@ body {
assert.deepStrictEqual(json.outputs[fileKey].inputs, { [makePath(file)]: { bytesInOutput: 14 } })
},

async metafileSplittingRelativeNewURL({ esbuild, testDir }) {
const entry = path.join(testDir, 'entry.js')
const worker = path.join(testDir, 'worker.js')
const outdir = path.join(testDir, 'out')
await writeFileAsync(entry, `
const workerURL = new URL("./worker.js", import.meta.url);
const blob = new Blob([\`import \${JSON.stringify(workerURL)};\`], { type: "text/javascript" });
new Worker(URL.createObjectURL(blob), { type: "module" }).addEventListener("message", console.log)
`)
await writeFileAsync(worker, `
postMessage("hello!")
`)
const result = await esbuild.build({
entryPoints: [entry],
bundle: true,
outdir,
metafile: true,
splitting: true,
format: 'esm',
})

const json = result.metafile
assert.strictEqual(Object.keys(json.inputs).length, 2)
assert.strictEqual(Object.keys(json.outputs).length, 2)
const cwd = process.cwd()
const makeOutPath = basename => path.relative(cwd, path.join(outdir, basename)).split(path.sep).join('/')
const makeInPath = pathname => path.relative(cwd, pathname).split(path.sep).join('/')

// Check metafile
const inEntry = makeInPath(entry);
const inWorker = makeInPath(worker);
const outEntry = makeOutPath(path.basename(entry));
const outWorkerChunk = makeOutPath('worker-UGPIWIMF.js');

assert.deepStrictEqual(json.inputs[inEntry], { bytes: 275, imports: [{ path: inWorker, kind: 'dynamic-import' }] })
assert.deepStrictEqual(json.inputs[inWorker], { bytes: 33, imports: [] })

assert.deepStrictEqual(json.outputs[outEntry].imports, [{ path: outWorkerChunk, kind: 'dynamic-import' }])
assert.deepStrictEqual(json.outputs[outWorkerChunk].imports, [])

assert.deepStrictEqual(json.outputs[outEntry].inputs, { [inEntry]: { bytesInOutput: 263 } })
assert.deepStrictEqual(json.outputs[outWorkerChunk].inputs, { [inWorker]: { bytesInOutput: 23 } })
},

// Test in-memory output files
async writeFalse({ esbuild, testDir }) {
const input = path.join(testDir, 'in.js')
Expand Down