sveltesvelte-3svelte-preprocess

svelte-preprocess does not transform typescript into javascript


I am trying to parse svelte component source codes in web worker. Full source code here

import { parse , preprocess } from 'svelte/compiler';
import sveltePreprocess from 'svelte-preprocess';

import {
  typescript,
  scss,
  globalStyle,
} from 'svelte-preprocess';


async function parseSvelte(source : string) {
  
  const preprocessedResult = await preprocess( source, [
    typescript({}),
    scss(),
    globalStyle(),
  ]);
  console.log(preprocessedResult);

  try {
  const ast = parse(preprocessedResult.code);
  console.log(ast);
  }
  catch(e) { console.log(e.toString() )}
}

I am using the above code to parse the following svelte component

<script lang="ts">
const x = (y : string) => {};
</script>

preprocess should transform the typescript into javascript, right? But preprocessedResult.code still contains typescript, and the subsequent parse failed.

Unexpected token (3:25)
1: 
2:           <script lang="ts">
3:             const x = (y : string) => {};
                            ^
4:             </script>

There is no error when calling preprocess method, please what is the problem here?


Solution

  • The issue in svelte-preprocess/src/transformers/typescript.ts line 497
    if (filename == null) return { code: content };

    When you call svelte.preprocess without the "optional" filename the typescript preprocessor does nothing.

    Call preprocess with the third argument to fix the issue:

    svelte.preprocess(code, processors, { filename: '/path/to/Component.svelte' })
                                          ^^^^^^^^
    

    (It doesn't even have to be a valid filename)

    I've reported the bug https://github.com/sveltejs/svelte-preprocess/issues/488