Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an npm package that I can import into sveltekit?

I would like to create a simple npm package and import that into svelte components, however, I cannot seem to use index files to import deeply nested files, e.g.

// routes/test.svelte
<script lang="ts">
  import { Test } from '@my-co/my-lib/dist/folder1/folder2/test';
  const test = new Test('foo', 'bar');
</script>

works, but

// routes/test.svelte
<script lang="ts">
  import { Test } from '@my-co/my-lib';
  const test = new Test('foo', 'bar');
</script>

does not. I have the following in the index.ts file in my npm module:

export { Test } from './folder1/folder2/test';

This strangely also does seem to work in ssr (dev server output in console seems to pick the import {Test} from '@my-co/my-lib' correctly), but not in the browser, where I get the error that Test is not a constructor...

Npm library package.json:

{
  "name": "@myco/my-lib",
  "version": "0.0.2",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "files": [
    "dist"
  ],
  "scripts": {
    "build": "tsc",
    "prepare": "npm run build"
  },
  "author": "redacted",
  "license": "ISC",
  "dependencies": {
    "@types/rosie": "0.0.40",
    "@types/slug": "^5.0.3",
    "rosie": "^2.1.0",
    "slug": "^5.1.1"
  }
}

Npm library tsconfig

{
  "compilerOptions": {
    "declaration": true,
    "strictNullChecks": true,
    "outDir": "dist",
    "moduleResolution": "node",
    "module": "es2015",
    "target": "es5",
    "sourceMap": true,
    "lib": ["es2015", "dom"],
    "rootDir": "src"
  },
  "include": ["src"],
  "exclude": ["node_modules", "dist"]
}

Lib structure

my-lib/
| dist/
| node_modules/
| src/
| | folder1/
| | | folder2/
| | | | test.ts

test.ts

export class Test {
  foo: string;
  bar: string;

  constructor(foo: string, bar: string) {
    this.foo = foo;
    this.bar = bar;
  }

  testMe() {
    console.log("foobar", this.foo, this.bar);
  }
}
like image 738
the_critic Avatar asked Nov 03 '25 17:11

the_critic


1 Answers

The svelte-kit package command should automatically do everything for you (docs).

This Youtube video should explain everything.

The steps it provides to publish are:

  1. npm init svelte@next project-name
  2. cd project-name
  3. Create component
  4. npx svelte-kit package
  5. cd package
  6. Login to npm / create an account
  7. npm publish --access public
like image 148
Caleb Irwin Avatar answered Nov 05 '25 15:11

Caleb Irwin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!