svelte-3 - 如何创建可以导入 sveltekit 的 npm 包?

标签 svelte-3 sveltekit

我想创建一个简单的 npm 包并将其导入到 svelte 组件中,但是,我似乎无法使用索引文件来导入深层嵌套的文件,例如

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

有效,但是

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

没有。我的 npm 模块的 index.ts 文件中有以下内容:

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

奇怪的是,这似乎在 ssr 中也有效(控制台中的开发服务器输出似乎正确地选择了 import {Test} from '@my-co/my-lib'),但在浏览器,在那里我得到 Test is not a constructor...

Npm 库 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 库 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"]
}

库结构

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);
  }
}

最佳答案

svelte-kit package 命令应该会自动为您完成一切 (docs)。

This Youtube video应该解释一切。

它提供的发布步骤是:

  1. npm init svelte@next project-name
  2. cd 项目名
  3. 创建组件
  4. npx svelte-kit 包
  5. cd包
  6. 登录到 npm/创建一个帐户
  7. npm publish --access public

关于svelte-3 - 如何创建可以导入 sveltekit 的 npm 包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70462440/

相关文章:

cypress - 使用 Svelte : Button is sometimes clicked, 的 Flaky cypress 测试有时不会

svelte - 将槽传递给递归组件

get - 使用静态适配器时如何在 sveltekit 上使用 get 参数?

import - 由 "ENV_VAR_NAME"导入的 RollupError : "$env/static/private" is not exported by "src/hooks.server.js", 。 - SvelteKit

svelte - 如何在 Svelte 中直接挂载 HTMLElement?

svelte - 如何返回 Svelte 组件的渲染 HTML?

svelte - 如何返回 svelte store 作为 promise 而不是带有订阅的对象

javascript - 没有 context=module 脚本标签的预加载函数

cloudflare - Sveltekit 开发与 workers KV -- 热重载

jwt - 在 sveltekit 中持久化用户状态