Skip to content

Commit

Permalink
fix: save & prepend original imports manually
Browse files Browse the repository at this point in the history
  • Loading branch information
lukeed committed Dec 16, 2020
1 parent 9e4a95f commit b1c7903
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ async function decide() {

const isExternal = /^(https?:)?\/\//;
const isString = (x: unknown): x is string => typeof x === 'string';
const IMPORTS = /import(?:["'\s]*([\w*{}\n,\r\s\t]+)from\s*)?["'\s].*([@\w/_-]+)["'\s].*/g;

function isTypescript(attrs: Attributes): boolean | void {
if (isString(attrs.lang)) return /^(ts|typescript)$/.test(attrs.lang);
Expand Down Expand Up @@ -89,6 +90,8 @@ async function transform(input: ProcessorInput, options: TransformOptions): Prom
}
}

let imports = input.content.match(IMPORTS);
let preprend = Array.isArray(imports) ? imports.join('\n') : '';
let output = await (service || esbuild).transform(input.content, config);

// TODO: format output.warnings
Expand All @@ -97,7 +100,7 @@ async function transform(input: ProcessorInput, options: TransformOptions): Prom
}

return {
code: output.code,
code: preprend + output.code.replace(IMPORTS, ''),
dependencies: deps,
map: output.map,
};
Expand Down
14 changes: 14 additions & 0 deletions test/fixtures/typescript.imports/Input.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<script lang="ts">
import Counter from './Counter.svelte';
import { capitalize } from './utils';
import {
hello, world,
howdy
} from 'foobar';
export let name: string = 'hello';
export const value = hello() + world();
</script>

<div>{capitalize(name)}</div>
<Counter {value} />
16 changes: 16 additions & 0 deletions test/fixtures/typescript.imports/Output.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<script lang="ts">import Counter from './Counter.svelte';

This comment has been minimized.

Copy link
@lukeed

lukeed Dec 16, 2020

Author Owner

Note that the lang="ts" in the Output is irrelevant. Svelte will drop this during its compilation.

import { capitalize } from './utils';
import {
hello, world,
howdy
} from 'foobar';
let name = "hello";
const value = hello() + world();
export {
name,
value
};
</script>

<div>{capitalize(name)}</div>
<Counter {value} />
5 changes: 5 additions & 0 deletions test/fixtures/typescript.imports/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { typescript } from '../../../src';

export const config = typescript({
//
})

0 comments on commit b1c7903

Please sign in to comment.