Git Product home page Git Product logo

svelte-dts's Introduction

Svelte dts

npm versionLicense: MITNode.js CI

Typescript declaration generator for svelte with typescript. Create the declaration files for your library and project. These are the main characteristics of this library:

✨ CLI(Command-line interface)
✨ Rollup plugin
✨ Svelte and typescript files

How it works?

The svelte-dts interpret the properties, events and slot properties in the svelte code, using typescript and svelte compiler. The svelte-dts too interpret typescript and declaration typescript code, and create default declarations for javascript code.

Observe the code of the click-counter-button library that has the ClickCounterButton component:

<script lang="ts">
  import { createEventDispatcher } from 'svelte';

  export let initialNumber: number = 0;

  let dispatch = createEventDispatcher<{ change: number }>();
  let number = initialNumber;

  $: dispatch('change', number);
</script>

<button on:click={() => (number += 1)}>Cliques: {number}</button>

The result is the generated typescript declarations. Please note below:

import { SvelteComponentTyped } from 'svelte';

declare module 'click-counter-button' {
  interface ClickCounterButtonProps {
    initialNumber: number;
  }

  class ClickCounterButton extends SvelteComponentTyped<ClickCounterButtonProps, { change: CustomEvent<number> }, {}> {}

  export default ClickCounterButton;
}

Installation

npm i svelte-dts
// OR
yarn add svelte-dts

Using with rollup

import typescript from '@rollup/plugin-typescript';
import svelte from 'rollup-plugin-svelte';
import autoPreprocess from 'svelte-preprocess';
import svelteDts from 'svelte-dts';

export default [
  {
    input: 'src/lib/App.svelte',
    external: ['svelte/internal'],
    plugins: [svelteDts(), svelte({ preprocess: autoPreprocess() }), typescript()],
  },
];

Options

Option Type Description Default
output string Declarations output file The value of pkg.types
extensions string[] Valid Extensions .svelte, .ts, .js

Using with cli

svelte-dts -i src/index.ts -o dist/index.d.ts

Options

Option Alias Description
--input [input] -i App input file
--output [output] -o Declarations output file
--extensions [extensions] -e Valid Extensions

NPM Statistics

Download stats for this NPM package

NPM

License

Svelte dts is open source software licensed as MIT.

svelte-dts's People

Contributors

andrelmlins avatar wallw-teal avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

svelte-dts's Issues

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'replace' of undefined

Hi.

Consider the following steps:

C:\git>git clone https://github.com/duallsistemas/duall-svelte-bootstrap5.git
cd duall-svelte-bootstrap5/
npm i
npm i svelte-dts -D
npx svelte-dts -i src/index.js -o src/index.d.ts

it raises the following error:

C:\git\duall-svelte-bootstrap5>npx svelte-dts -i src/index.js -o src/index.d.ts
(node:15504) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'replace' of undefined
    at TypescriptTransformer.toString (C:\git\duall-svelte-bootstrap5\node_modules\svelte-dts\dist\transformer\typescript.js:61:14)
    at TypescriptTransformer.<anonymous> (C:\git\duall-svelte-bootstrap5\node_modules\svelte-dts\dist\transformer\typescript.js:72:55)
    at Generator.next (<anonymous>)
    at C:\git\duall-svelte-bootstrap5\node_modules\svelte-dts\dist\transformer\typescript.js:27:71
    at new Promise (<anonymous>)
    at __awaiter (C:\git\duall-svelte-bootstrap5\node_modules\svelte-dts\dist\transformer\typescript.js:23:12)
    at TypescriptTransformer.appendFile (C:\git\duall-svelte-bootstrap5\node_modules\svelte-dts\dist\transformer\typescript.js:70:16)
    at C:\git\duall-svelte-bootstrap5\node_modules\svelte-dts\dist\generator.js:111:70
    at Array.map (<anonymous>)
    at Generator.<anonymous> (C:\git\duall-svelte-bootstrap5\node_modules\svelte-dts\dist\generator.js:111:49)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:15504) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:15504) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Is this a bug, or I'm doing something wrong? 😕

TIA for any help!

Module has no exported member error in `package.json` of `types`

// package.json
  "name": "awesome-components",
  "types": "./dist/index.d.ts",

Not working:

import { SvelteComponentTyped } from "svelte";

declare module 'awesome-components' {
  export const register: (...cpn: any[]) => any;
  export { default as WcSwitch } from './WcSwitch.svelte';
}

declare module 'awesome-components/WcSwitch.svelte' {
  interface WcSwitchProps {
    checked: boolean;
  }

  export default class WcSwitch extends SvelteComponentTyped<
    WcSwitchProps,
    {  },
    {  }
  > {}
}

Worked:

import { SvelteComponentTyped } from "svelte";

- declare module 'awesome-components' {
  export const register: (...cpn: any[]) => any;
  export { default as WcSwitch } from './WcSwitch.svelte';
- }

declare module 'awesome-components/WcSwitch.svelte' {
  interface WcSwitchProps {
    checked: boolean;
  }

  export default class WcSwitch extends SvelteComponentTyped<
    WcSwitchProps,
    {  },
    {  }
  > {}
}

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received undefined

Hi, would you consider adding Vite support ?

19:52:32 [vite] vite.config.js changed, restarting server...
error when starting dev server:
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received undefined
    at new NodeError (node:internal/errors:372:5)
    at validateString (node:internal/validators:120:11)
    at Object.isAbsolute (node:path:403:5)
    at new Generator (C:\wamp64\www\msd2\node_modules\svelte-dts\dist\generator.js:50:37)
    at Context.<anonymous> (C:\wamp64\www\msd2\node_modules\svelte-dts\dist\svelteDts.js:23:29)
    at Generator.next (<anonymous>)
    at C:\wamp64\www\msd2\node_modules\svelte-dts\dist\svelteDts.js:8:71
    at new Promise (<anonymous>)
    at __awaiter (C:\wamp64\www\msd2\node_modules\svelte-dts\dist\svelteDts.js:4:12)
    at Context.buildStart (C:\wamp64\www\msd2\node_modules\svelte-dts\dist\svelteDts.js:22:20)
error Command failed with exit code 1.

package.json

{
"devDependencies": {
    "@types/bootstrap": "^5.1.12",
    "@types/nprogress": "^0.2.0",
    "tailwindcss": "^3.1.6",
    "vite": "^3",
    "vite-define-envs-plugin": "^0.1.1",
    "vite-plugin-symfony": "^0.3.1"
  },
  "dependencies": {
    "@inertiajs/inertia": "^0.11.0",
    "@inertiajs/inertia-svelte": "^0.8.0",
    "@inertiajs/progress": "^0.2.7",
    "@sveltejs/vite-plugin-svelte": "^1.0.1",
    "autoprefixer": "^10.4.7",
    "axios": "^0.27.2",
    "gsap": "^3.10.4",
    "nouislider": "^15.6.0",
    "nprogress": "^0.2.0",
    "path": "^0.12.7",
    "postcss": "^8.4.14",
    "postcss-scss": "^4.0.4",
    "sass": "^1.54.0",
    "svelte": "^3.49.0",
    "svelte-content-loader": "^1.1.3",
    "svelte-dts": "^0.3.7",
    "svelte-motion": "^0.11.2",
    "svelte-preprocess": "^4.10.7",
    "svelte-previous": "^2.1.1",
    "swr": "^1.3.0",
    "typescript": "^4.7.4"
  },
}

vite.config.js

import { defineConfig } from "vite"
import symfonyPlugin from "vite-plugin-symfony"
import { svelte } from '@sveltejs/vite-plugin-svelte'
import sveltePreprocess from 'svelte-preprocess'
import svelteDts from 'svelte-dts'
import dns from 'dns'

dns.setDefaultResultOrder('verbatim')

export default defineConfig({
    plugins: [
        symfonyPlugin(),
        svelteDts(),
        svelte({
            preprocess: [sveltePreprocess({ typescript: true })],
            experimental: {
                prebundleSvelteLibraries: true,
            },
            hot: {
                // preserveLocalState: true,
            }
        }),
    ],
    server: {
        host: "127.0.0.1",
        hmr: true
    },
    root: ".",
    base: "/build/",
    build: {
        manifest: true,
        emptyOutDir: true,
        assetsDir: "",
        outDir: "./public/build",
        rollupOptions: {
            input: {
                app: "./assets/App/app.js",
                presentation: "./assets/presentation/presentation.ts",
            },
        },
    },
    resolve: {
        dedupe: ["axios", "svelte-motion", "framer-motion", "gsap", "nouislider"],
    },
});

The svelte-dts is duplicating types and properties

Hi.

Supposing we run the svelte-dts in this small project, some generated types are duplicated, e.g:

import { SvelteComponentTyped } from "svelte";

declare module '@duallsistemas/duall-svelte-bootstrap5';

declare module '@duallsistemas/duall-svelte-bootstrap5/types.ts' {
	export type BackgroundColor = 'primary' | 'secondary' | 'success' | 'danger' | 'warning' | 'info' | 'light' | 'dark' | 'body' | 'white' | 'transparent';
	export type AlertType = 'primary' | 'secondary' | 'success' | 'danger' | 'warning' | 'info' | 'light' | 'dark';
	export type ButtonType = 'primary' | 'secondary' | 'success' | 'danger' | 'warning' | 'info' | 'light' | 'dark' | 'link';
	export type ButtonSize = 'sm' | 'lg';
	export type ModalSize = 'sm' | 'lg' | 'xl' | 'fullscreen';
}

declare module '@duallsistemas/duall-svelte-bootstrap5';

declare module '@duallsistemas/duall-svelte-bootstrap5/utils.ts' {
	export function makeId(): string;
}

declare module '@duallsistemas/duall-svelte-bootstrap5/types.ts' {
	export type BackgroundColor = 'primary' | 'secondary' | 'success' | 'danger' | 'warning' | 'info' | 'light' | 'dark' | 'body' | 'white' | 'transparent';
	export type AlertType = 'primary' | 'secondary' | 'success' | 'danger' | 'warning' | 'info' | 'light' | 'dark';
	export type ButtonType = 'primary' | 'secondary' | 'success' | 'danger' | 'warning' | 'info' | 'light' | 'dark' | 'link';
	export type ButtonSize = 'sm' | 'lg';
	export type ModalSize = 'sm' | 'lg' | 'xl' | 'fullscreen';
}

declare module '@duallsistemas/duall-svelte-bootstrap5/utils.ts' {
	export function makeId(): string;
}
...

and properties:

declare module '@duallsistemas/duall-svelte-bootstrap5/Button.svelte' {
	interface ButtonProps {
		ref?: HTMLButtonElement | HTMLAnchorElement;
		type?: ButtonType;
		title?: string;
		hint?: string;
		icon?: string;
		href?: string;
		disabled?: boolean;
		loading?: boolean;
		loadingMessage?: string;
		size?: ButtonSize;
		ref?: HTMLButtonElement | HTMLAnchorElement;
		type?: ButtonType;
		title?: string;
		hint?: string;
		icon?: string;
		href?: string;
		disabled?: boolean;
		loading?: boolean;
		loadingMessage?: string;
		size?: ButtonSize;
	}

I have been trying this configuration:

export default {
  input: pkg.svelte,
  plugins: [
    svelteDts({
      output: pkg.types
    }),
...

So, is there any option to avoid those duplications to generate a smaller .d.ts file?

TIA for any help!

[!] (plugin svelte-dts) TypeError: Cannot read properties of undefined (reading 'output')

Hi guys!
I've added this library to a project but Im receiving this error, I dont know what I did wrong.

[!] (plugin svelte-dts) TypeError: Cannot read properties of undefined (reading 'output')

My rollup config looks like this:

import svelte from 'rollup-plugin-svelte';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import typescript from '@rollup/plugin-typescript';
import autoPreprocess from 'svelte-preprocess';
import svelteDts from 'svelte-dts';

import pkg from './package.json';

const name = pkg.name
  .replace(/^(@\S+\/)?(svelte-)?(\S+)/, '$3')
  .replace(/^\w/, (m) => m.toUpperCase())
  .replace(/-\w/g, (m) => m[1].toUpperCase());

export default {
  input: 'src/index.svelte',
  output: [
    { file: pkg.module, format: 'es' },
    { file: pkg.main, format: 'umd', name },
  ],
  plugins: [
    svelteDts(),
    resolve(),
    commonjs(),
    svelte({ preprocess: autoPreprocess() }),
    typescript(),
  ],
};

[FEATURE REQUEST] Options.input

Hi.

It would by nice to allow the user to specify the input origin, for example:

export default {
  input: 'src/index.js',
  plugins: [
    svelteDts({ input: "src/index.js" }), // or { input: [ "src/foo.js", "src/bar.js" ] }
...

cheers

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.