4

I'm new to Svelte. Quick question:

Is there a CLI for the Svelte compiler, and how do I access it?

I understand Svelte has a preconfigured setup that uses rollup and what not for building an app. That's all good, but I only need the CLI for transforming a svelte file to pure js file. Something like:

svelte compile input.svelte --out=out.js

Update It seems like there is no CLI for the Svelte compiler. However, a brief outline of the compilation process is available here. In particular,the following code snippet, which can be used to build CLI.

result: {
    js,
    css,
    ast,
    warnings,
    vars,
    stats
} = svelte.compile(source: string, options?: {...})

1 Answer 1

3

For Svelte 3 there is no official CLI.

You'll either write one:

#!/usr/bin/env node
import { compile } from "svelte/compiler";
import fs from "node:fs";

const filename = process.argv[2];
const source = fs.readFileSync(filename, 'utf-8');
const result = compile(source, { filename });
process.stdout.write(result.js.code);

and customize that script to your exact needs (Custom compile options and/or run additional preprocessors for TypeScript support etc)

But most cases an existing build tool is a better option
and for most build tools there is plugin (vite) or loader (webpack) available for Svelte.

Sign up to request clarification or add additional context in comments.

4 Comments

Would this consider compile options from somewhere or could we pass compile options somehow. Use-case is to create a custom element from an otherwise existing component within a Sveltekit project.
'compile()' will get compile options as second argument, I just checked. So we could expose some options as CLI tool arguments and pass them to the compiler.
compile's first argument is the source code string, not filename svelte.dev/docs#compile-time-svelte-compile
Oops, it created a component that just displays the filename 😅. I've updated the answer so it loads and uses the source from the filename.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.