我正在开发一个 monorepo,并且正在尝试创建一个成为 React ui-kit 库的包。目前,我一直在尝试导出自定义按钮组件并使用 Vite 构建 ESM 和 CJS 模块。
但是当我用 Vite 构建它时,我收到此错误:
Module './components/button.js' was resolved to '[...]/libs/ui/src/components/button.tsx', but '--jsx' is not set.
这是组件
// src/components/button.tsx
import React, { ComponentProps } from 'react'
import "../index.css";
export function Button(props: Omit<ComponentProps<'button'>, 'className'>) {
return <button className="bg-blue-500 text-white px-4 py-2 rounded" {...props} />;
}
// src/main.ts
export { Button } from './components/button.js';
这是
Vite
配置以及 tsconfig
:
// vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// export type definition files
import dts from 'vite-plugin-dts'
import path from 'path'
import packageJson from './package.json'
export default defineConfig({
root: '/',
plugins: [react(), dts({ include: 'src' })],
build: {
// build package as a library
lib: {
entry: path.resolve(__dirname, 'src/index.ts'),
// es = ES module
formats: ['es', 'cjs']
},
rollupOptions: {
// avoid bundling react and react-dom
// as they will be already required and bundled by the user app
// using this application
external: ['react', 'react-dom', 'react/jsx-runtime', 'tailwindcss']
},
sourcemap: true
}
})
// tsconfig.json
{
"extends": "../../tsconfig.json",
"include": ["src/**/*.ts", "src/**/*.tsx"],
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"jsx": "react-jsx",
"resolveJsonModule": true
},
"exclude": ["node_modules/"]
}
如果我没有将
react/jsx-runtime
设置为外部依赖项,则会收到另一个错误:
error during build:
[vite]: Rollup failed to resolve import "react/jsx-runtime" from "[...]/libs/ui/src/components/button.tsx".
我不知道我的配置出了什么问题?
显然这是因为
root
中的 vite.config.ts
选项。无论如何,这是没有必要的,所以我删除了它,现在它可以工作了。