diff options
author | Kitson Kelly <me@kitsonkelly.com> | 2020-02-27 03:59:33 +1100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-02-26 17:59:33 +0100 |
commit | 671f0b83be5cf9f9b6b1d667d41fd7779896a21a (patch) | |
tree | a53bf8ed33b3921260170ab1ace40e3a77374661 /cli/js | |
parent | 942e67c00b8ebdf6671fc8bb2e6c78c3ad8b3ff8 (diff) |
Bundles can be sync or async based on top level await (#4124)
Previously, bundles always utilised top level await, even if the bundled
modules didn't require top level await. Now, analysis of the bundle is
done and if none of the bundled modules are asynchronously executed,
then the bundle as a whole will be synchronously executed.
Fixes #4055
Fixes #4123
Diffstat (limited to 'cli/js')
-rw-r--r-- | cli/js/compiler_api_test.ts | 4 | ||||
-rw-r--r-- | cli/js/compiler_bundler.ts | 13 |
2 files changed, 13 insertions, 4 deletions
diff --git a/cli/js/compiler_api_test.ts b/cli/js/compiler_api_test.ts index a6baecbf5..82f72cdef 100644 --- a/cli/js/compiler_api_test.ts +++ b/cli/js/compiler_api_test.ts @@ -94,14 +94,14 @@ test(async function bundleApiSources() { "/bar.ts": `export const bar = "bar";\n` }); assert(diagnostics == null); - assert(actual.includes(`__inst("foo")`)); + assert(actual.includes(`__inst_s("foo")`)); assert(actual.includes(`__exp["bar"]`)); }); test(async function bundleApiNoSources() { const [diagnostics, actual] = await bundle("./cli/tests/subdir/mod1.ts"); assert(diagnostics == null); - assert(actual.includes(`__inst("mod1")`)); + assert(actual.includes(`__inst_s("mod1")`)); assert(actual.includes(`__exp["printHello3"]`)); }); diff --git a/cli/js/compiler_bundler.ts b/cli/js/compiler_bundler.ts index b9893620a..f8f0b48e8 100644 --- a/cli/js/compiler_bundler.ts +++ b/cli/js/compiler_bundler.ts @@ -42,9 +42,16 @@ export function buildBundle( rootName = normalizeUrl(rootName) .replace(sharedPath, "") .replace(/\.\w+$/i, ""); + // If one of the modules requires support for top-level-await, TypeScript will + // emit the execute function as an async function. When this is the case we + // need to bubble up the TLA to the instantiation, otherwise we instantiate + // synchronously. + const hasTla = data.match(/execute:\sasync\sfunction\s/); let instantiate: string; if (rootExports && rootExports.length) { - instantiate = `const __exp = await __inst("${rootName}");\n`; + instantiate = hasTla + ? `const __exp = await __inst("${rootName}");\n` + : `const __exp = __inst_s("${rootName}");\n`; for (const rootExport of rootExports) { if (rootExport === "default") { instantiate += `export default __exp["${rootExport}"];\n`; @@ -53,7 +60,9 @@ export function buildBundle( } } } else { - instantiate = `await __inst("${rootName}");\n`; + instantiate = hasTla + ? `await __inst("${rootName}");\n` + : `__inst_s("${rootName}");\n`; } return `${SYSTEM_LOADER}\n${data}\n${instantiate}`; } |