Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feat] add SveltePreprocessor utility type #7742

Merged
merged 1 commit into from
Aug 1, 2022

Conversation

metonym
Copy link
Contributor

@metonym metonym commented Jul 31, 2022

This PR adds a utility to type Svelte preprocessors. It aims to improve the DX for authors writing Svelte preprocessors using TypeScript. It was inspired by #7121, which added a utility Action type to strongly type Svelte actions.

Current DX

The current workflow is to use the PreprocessorGroup type.

import type { PreprocessorGroup } from "svelte/types/compiler/preprocess";

function preprocessor(): Pick<PreprocessorGroup<"markup">> {
  return {
    markup({ content }) {
      return { code: content };
    },
  };
}

However, since a preprocessor is usually a function that returns a function to allow user-provided options, it would be more concise for a utility type to select from the various groups (markup/style/script) and optionally add a generic options as the second parameter.

Proposed DX

The following examples illustrate basic use cases:

  • preprocessor with a single group
  • preprocessor with multiple groups
  • preprocessor with user-provided options
import type { SveltePreprocessor } from "svelte/types/compiler/preprocess";

// Markup-only preprocessor without options
const preprocessMarkup: SveltePreprocessor<"markup"> = () => {
  return {
    markup({ content }) {
      return { code: content };
    },
  };
};

// Markup and style preprocessor without options
const preprocessMarkupStyles: SveltePreprocessor<"markup" | "style"> = () => {
  return {
    markup({ content }) {
      return { code: content };
    },
    style({ content }) {
      return { code: content };
    },
  };
};

// Script preprocessor with user options
// Options are passed as the second parameter
const preprocessWithOptions: SveltePreprocessor<"script", { sourcemap?: boolean }> = (options) => {
  const sourcemap = options?.sourcemap === true;

  return {
    script({ content }) {
      return { code: content, map: sourcemap ? "..." : undefined };
    },
  };
};

Copy link
Member

@dummdidumm dummdidumm left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice!

@dummdidumm dummdidumm merged commit 439bbf8 into sveltejs:master Aug 1, 2022
@Conduitry
Copy link
Member

This has been released in 3.50.0. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants