0

I want to create a npm package, called 'my-pkg', and also I want to have a simple test website to test the package under the same project.

Here is my folder structure:

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

below is my vite config file:

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

in my tsconfig.json, I have configured path, and in vscode it works fine.

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

Now when I run vite build, I can get the package I want, but when I run vite server to start the test website, it tells me cannot find 'my-pkg'. Why doesn't the alias work in my test site? How to resolve this?

Thanks in advance.

1 Answer 1

0

You need create two modes in vite.config.js or use different config,Because you entry file always is src/index.ts. After creating a config or a mode that config entry file is server/ index.ts

Sign up to request clarification or add additional context in comments.

1 Comment

if you define output file is dist/main.js,you can just import use 'import you-pkg from "../"'. In your config, you should set alias to '../'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.