Vite、NPM、React 组件库 无效的 hook 调用、外部问题?

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

我能够将我的 React 组件库捆绑在 Rollup 中,但我想要使用 Vite 的功能进行开发并在周末安装。我的问题是,现在当我尝试使用另一个反应项目

npm link
我的 vite 生成的发行版时,出现以下错误。 error

基本上,它是说当它获取“Provider”时不能使用 useContext,这实际上只是一个 React 上下文。当它尝试加载它时,包中似乎出现了问题:

var Context=/*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createContext(null);

我的 vite 配置如下:

export default defineConfig({
  plugins: [react(), dts({ insertTypesEntry: true })],
  build: {
    lib: {
      entry: path.resolve(__dirname, "src/lib/index.ts"),
      name: "MyLib",
      formats: ["umd", "es"],
      fileName: (format) => `my-lib.${format}.js`,
    },
    rollupOptions: {
      external: [ "react", "react-dom" ]
    }
  },
});

搜了一下说可能是我的依赖有问题,使用了react或者react-dom两个版本。我已经尝试过我能想到的所有依赖配置,但它们都以不同的方式中断。我想也许 npm 缓存可能会让我感到困惑或者其他什么。

有什么想法吗? Vite 在“开发”模式下工作正常,并且组件在 Rollup 中工作正常,所以我觉得这只是一个我不明白的愚蠢配置

reactjs npm vite rollupjs
1个回答
0
投票

我遇到了同样的问题并尝试了很多方法,这最终对我有用:

1- 将

react
react-dom
移至
peerDependancies

2- 将

rollupOptions
添加到您的构建中
vite.config.ts

rollupOptions: {
  external: [ 'react', 'react-dom' ]
},

3- 在

build
之后添加以下内容:

  resolve: {
    dedupe: ['react', 'react-dom'],
  },

以下是有关解析功能的更多信息: https://vitejs.dev/config/shared-options.html#resolve-dedupe

这是我最终的

vite.config.ts
的样子:

export default defineConfig({
  plugins: [
    react(),
    eslintPlugin({
      include: ['src/**/*.js', 'src/**/*.ts', 'src/**/*.tsx'], // include files to lint
      exclude: ['node_modules', 'dist'], // exclude files from linting
      fix: true, // enable auto-fixing
      extensions: ['.js', '.ts', '.tsx'], // file extensions to lint
      emitError: true, // emit errors instead of warnings
      failOnError: true, // throw an error when there are lint errors
      lintOnStart: true, // lint on start-up
    }),
    stylelintPlugin({
      fix: true,
      include: ['src/**/*.css'],
      exclude: ['node_modules', 'dist'],
      emitError: true,
      emitWarning: true,
    }),
  ],
  build: {
    outDir: 'dist',
    lib: {
      entry: 'src/index.ts', // Specify the entry point for your library
      name: '***YOUR_PROJECT***', // Specify the name of your library (will be available as a global variable)
      fileName: 'index', // Specify the desired file name for the output library file
      formats: ['es', 'umd'], // Specify formats of output library
    },
    rollupOptions: {
      external: [ 'react', 'react-dom' ]
    },
  },
  resolve: {
    dedupe: ['react', 'react-dom'],
  },
});
© www.soinside.com 2019 - 2024. All rights reserved.