reactjs Vite/Storybook组件库无法安装到消费库中

db2dz4w8  于 2023-04-11  发布在  React
关注(0)|答案(1)|浏览(139)

我已经用Vite在Storybook上创建了一个组件库。该组件库用于将我们公司的所有组件存储在一个中心位置。
它作为自己的存储库存在,并有一个npm注册表,然后通过npm安装在消费项目中。
这是组件库中的vite.config.ts

export default defineConfig({
  build: {
    lib: {
      entry: {
        components: path.resolve(__dirname, "src/index.ts"),
      },
      fileName: (format, entry) =>
        `name-component-library.${entry}.${format}.js`,
      formats: ["es", "umd"],
      name: "nameComponents",
    },
    rollupOptions: {
      // An array of module IDs to exclude from the final bundle
      external: ["react", "react-dom"],
      // Defines the output configuration for your bundle
      output: {
        // Maps module IDs to their corresponding global variable names
        globals: {
          react: "React",
          "react-dom": "ReactDOM",
        },
      },
    },
  },
  plugins: [
    react(),
    tsConfigPaths(),
    dts({
      include: ["src"],
    }),
  ],
});

组件库使用MUI v5组件和一些其他库(例如react-responsive-carousel)实现。
这些是大的依赖关系:

"@emotion/react": "^11.10.6",
"@emotion/styled": "^11.10.6",
"@material-ui/core": "^4.12.4",
"@mui/icons-material": "^5.11.16",
"@mui/material": "^5.11.16",

在消费项目中,我检查了node_modules,我看到了库。构建的所有内容都在那里。它还有自己的node_modules,其中包含上面显示的依赖项。
消费项目和组件库都使用React 18。
然而,当消费项目试图编译时,我得到了这个错误:

./node_modules/@name/component-library/dist/name-component-library.components.es.js 1126:58
Module parse failed: Unexpected token (1126:58)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|             var h = e ? e() : "";
|             I(
>               "Failed " + Z + " type: " + W.message + (h ?? "")
|             );
|           }

我快没主意了。
组件库package.json看起来像这样:

"name": "@name/component-library",
  "private": false,
  "version": "2.1.6",
  "type": "module",
  "main": "./dist/name-component-library.components.umd.js",
  "module": "./dist/name-component-library.components.es.js",
  "types": "./dist/index.d.ts",
  "files": [
    "dist"
  ],
w8rqjzmb

w8rqjzmb1#

因为我公司的代码库完全是狗屎,我从来没有想过我们没有实现babel转译器。

module: {
    rules: [
        {
            test: /\.(js|jsx|ts|tsx)$/,
            exclude: /node_modules\/(?!(@name\/component-library)\/).*/,
            use: {
                loader: 'babel-loader',
                options: {
                    presets: [
                        '@babel/preset-env',
                        '@babel/preset-react',
                        '@babel/preset-typescript'
                    ]
                }
            }
        }
    ]
},

相关问题