Fix using async functions by modifying svelte-preprocess output

This commit is contained in:
Henrik Giesel 2022-02-26 18:12:41 +01:00
parent 94edaa5e97
commit 94c9cadaaa

View file

@ -7,7 +7,7 @@ import * as worker from "@bazel/worker";
import { svelte2tsx } from "svelte2tsx"; import { svelte2tsx } from "svelte2tsx";
import preprocess from "svelte-preprocess"; import preprocess from "svelte-preprocess";
import { basename } from "path"; import { basename } from "path";
import * as ts from "typescript"; import ts from "typescript";
import * as svelte from "svelte/compiler"; import * as svelte from "svelte/compiler";
const parsedCommandLine: ts.ParsedCommandLine = { const parsedCommandLine: ts.ParsedCommandLine = {
@ -133,6 +133,21 @@ function readFile(file: string): Promise<string> {
return fs.promises.readFile(file, "utf-8"); return fs.promises.readFile(file, "utf-8");
} }
// https://github.com/sveltejs/svelte-preprocess/issues/373
function removeDuplicatedAwaitImport(code: string): string {
const regex = /import { __awaiter } from \"tslib\";/g;
let first = true;
return code.replace(regex, (substring: string): string => {
if (first) {
first = false;
return substring;
}
return "";
});
}
async function compileSingleSvelte( async function compileSingleSvelte(
input: SvelteInput, input: SvelteInput,
binDir: string, binDir: string,
@ -157,12 +172,15 @@ async function compileSingleSvelte(
const processed = await svelte.preprocess(input.data, preprocessOptions, { const processed = await svelte.preprocess(input.data, preprocessOptions, {
filename: input.path, filename: input.path,
}); });
const result = svelte.compile(processed.toString!(), { const processedString = removeDuplicatedAwaitImport(processed.toString!());
const result = svelte.compile(processedString, {
format: "esm", format: "esm",
css: false, css: false,
generate: "dom", generate: "dom",
filename: input.mjsPath, filename: input.mjsPath,
}); });
// warnings are an error // warnings are an error
if (result.warnings.length > 0) { if (result.warnings.length > 0) {
console.log(`warnings during compile: ${result.warnings}`); console.log(`warnings during compile: ${result.warnings}`);
@ -177,7 +195,7 @@ async function compileSingleSvelte(
result.js.code; result.js.code;
await writeFile(input.mjsPath, outputSource); await writeFile(input.mjsPath, outputSource);
} catch (err) { } catch (err) {
console.log(`compile failed: ${err}`); console.log(`Compile failed: ${err}`);
return; return;
} }
} }