Vite.js 使用 lib 选项构建未加载 React 应用程序

Vite.js build with lib option not loading react app

下面是我当前的 vite config.js/ package.json 和 tsconfig.json 与 lib 配置的构建,它可以正常使用正常的 vite 构建但失败不适用于构建库

文件在 dist 文件夹中生成,但应用程序未加载

邀请.config.js

`/* eslint-disable import/no-extraneous-dependencies */

import reactRefresh from '@vitejs/plugin-react-refresh';
import path from 'path';
import { Alias, defineConfig } from 'vite';
import * as tsconfig from './tsconfig.paths.json';

function readAliasFromTsConfig(): Alias[] {
  const pathReplaceRegex = new RegExp(/\/\*$/, '');
  return Object.entries(tsconfig.compilerOptions.paths).reduce(
    (aliases, [fromPaths, toPaths]) => {
      const find = fromPaths.replace(pathReplaceRegex, '');
      const toPath = toPaths[0].replace(pathReplaceRegex, '');
      const replacement = path.resolve(__dirname, toPath);
      aliases.push({ find, replacement });
      return aliases;
    },
    [] as Alias[],
  );
}

export default defineConfig({
  build: {
    lib: {
      entry: path.resolve(__dirname, "src/main.tsx"),
      name: "Aagam",
    },
    rollupOptions: {
      external: ["react"],
      output: {
        // Provide global variables to use in the UMD build
        // for externalized deps
        globals: {
          react: 'React',
        },
      },
    },
    minify: true,
    sourcemap: false,
  },
  plugins: [reactRefresh()],
  resolve: {
    alias: readAliasFromTsConfig(),
  },
  css: {
    modules: { localsConvention: 'camelCase' },
    preprocessorOptions: {
      scss: {
        additionalData: `$injectedColor: orange;`
      }
    }
  }
});

> `

package.json

  "name": "reporting-ui-component",
  "version": "1.0.0",
  "files": [
    "dist"
  ],
  "typings": "./dist/reporting-ui-component.d.ts",
  "main": "./dist/reporting-ui-component.umd.js",
  "module": "./dist/reporting-ui-component.es.js",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build && tsc -P tsconfig.dts.json",
    "serve": "vite preview",
    "start": "npm run dev",
    "lint:fix": "eslint src --ext .jsx,.js,.ts,.tsx --quiet --fix",
    "lint:format": "prettier  --loglevel warn --write \"./**/*.{js,jsx,ts,tsx,css,md,json}\" ",
    "lint": "yarn lint:format && yarn lint:fix ",
    "type-check": "tsc",
    "lint-staged": "npx lint-staged -r",
    "validate": "npm run style",
    "validate-commit": "npm run lint-staged",
    "style": "npx -q eslint src --ext .ts,.tsx --fix"
  }

tsconfig.dts.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "noEmit": false,
    "declaration": true,
    "declarationDir": "dist",
    "emitDeclarationOnly": true
  },
  "include": ["src"]
}

如果能提供一些解决方案就好了? 我在 config

以上的 运行 上遇到错误

为了确保您的项目是从 lib 生成的输出中呈现的,请确保引用您的应用程序的起点,即 index.html 以具有以下脚本

 <script src="/dist/<your-file-name>.umd.js"></script>

代替之前的路径

 <script type="module" src="/src/main.tsx"></script>

它应该开始工作了