如何使用Vite创建带有测试网站的npm包?

问题描述 投票:0回答:1

我想创建一个npm包,名为'my-pkg',并且我想有一个简单的测试网站来测试同一项目下的包。

这是我的文件夹结构:

my-pkg
  server // test website folder
    index.tsx // here will import the package
    index.html
  src
    index.tsx // package source code
  vite.config.ts

下面是我的 vite 配置文件:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import dts from "vite-plugin-dts";
import * as path from "path";

export default defineConfig({
    plugins: [
        react(),
        dts({
            include: ["src/**/*.tsx"],
        }),
    ],
    build: {
        lib: {
            entry: [path.resolve(__dirname, "src/index.tsx")],
            formats: ["umd"],
            fileName: (format) => `my-pkg.${format}.js`,
            name: "MyPkg",
        },
        rollupOptions: {
            external: ["react", "react-dom"],
            output: {
                globals: {
                    react: "React",
                    "react-dom": "ReactDOM"
                },
            },
        },
        cssCodeSplit: true,
        sourcemap: true,
        assetsInlineLimit: Infinity,
    },
    resolve: {
        alias: { // I use this alias because I want my test site can use import from 'my-pkg'
            "my-pkg": path.resolve(__dirname, "./src/index.tsx")
        },
    },
    server: {
        host: "localhost",
        port: 3000,
        open: "/server/index.html",
        strictPort: true,
        fs: {
            cachedChecks: false,
        },
    },
});

在我的 tsconfig.json 中,我已经配置了路径,并且在 vscode 中它工作正常。

"paths": {
   "my-pkg: ["./src/index.tsx"]
}

现在当我运行

vite build
时,我可以获得我想要的包,但是当我运行
vite server
启动测试网站时,它告诉我找不到'my-pkg'。为什么别名在我的测试站点中不起作用?怎么解决这个问题?

提前致谢。

vite npm-package
1个回答
0
投票

您需要在 vite.config.js 中创建两种模式或使用不同的配置,因为您的入口文件始终是 src/index.ts。 创建配置或模式后,配置入口文件为 server/index.ts

© www.soinside.com 2019 - 2024. All rights reserved.