
本文旨在解决在使用 Rollup 构建 React 组件库时,组件内部引用其他自写组件时遇到的 "Unresolved dependencies" 错误。通过配置 Rollup 插件和 tsconfig.json 文件,确保组件库能够正确解析和打包内部依赖关系,最终成功构建可用的组件库。
在使用 Rollup 构建组件库时,经常会遇到组件内部引用其他自写组件导致构建失败的问题,错误信息通常类似于 "Unresolved dependencies"。 这通常是由于 Rollup 无法正确解析组件之间的依赖关系,尤其是当涉及到 TypeScript 和 CSS 模块时。以下提供一种解决方案,通过适当配置 rollup.config.mjs 和 tsconfig.json 文件,确保 Rollup 能够正确处理这些依赖关系。
rollup.config.mjs 文件是 Rollup 的核心配置文件,需要确保以下几点:
以下是一个示例 rollup.config.mjs 文件:
import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import typescript from "@rollup/plugin-typescript";
import { terser } from 'rollup-plugin-terser';
import external from 'rollup-plugin-peer-deps-external'
import postcss from 'rollup-plugin-postcss'
import dts from "rollup-plugin-dts";
import packageJson from "./package.json";
export default [
{
input: "src/index.ts",
output: [
{
file: packageJson.main,
format: "cjs",
sourcemap: true,
name: 'ui-components'
},
{
file: packageJson.module,
format: "esm",
sourcemap: true,
},
],
plugins: [
resolve(),
commonjs(),
external(),
postcss(),
terser(),
typescript({ tsconfig: "./tsconfig.json" }),
],
},
{
input: "dist/esm/types/index.d.ts",
output: [{ file: "dist/index.d.ts", format: "esm" }],
external: [/\.css$/],
plugins: [dts.default()],
},
];注意: 在生成声明文件 .d.ts 的配置中,需要添加 external: [/\.css$/],以避免将 CSS 文件包含在声明文件中。
tsconfig.json 文件用于配置 TypeScript 编译器。以下是一些重要的配置项:
PHP经典实例(第2版)能够为您节省宝贵的Web开发时间。有了这些针对真实问题的解决方案放在手边,大多数编程难题都会迎刃而解。《PHP经典实例(第2版)》将PHP的特性与经典实例丛书的独特形式组合到一起,足以帮您成功地构建跨浏览器的Web应用程序。在这个修订版中,您可以更加方便地找到各种编程问题的解决方案,《PHP经典实例(第2版)》中内容涵盖了:表单处理;Session管理;数据库交互;使用We
453
以下是一个示例 tsconfig.json 文件:
{
"compilerOptions": {
"target": "es2016",
"jsx": "react",
"module": "ESNext",
"moduleResolution": "node",
"declaration": true,
"emitDeclarationOnly": true,
"sourceMap": true,
"outDir": "dist",
"declarationDir": "types",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipDefaultLibCheck": true,
"skipLibCheck": true,
"allowImportingTsExtensions": true,
"baseUrl": "src",
"rootDir": "src",
"paths": {
"atoms/*": [
"atoms/*"
],
"molecules/*": [
"molecules/*"
],
"styles/*": [
"styles/*"
]
}
}
}确保组件内部的模块导入路径是正确的。使用 baseUrl 和 paths 配置可以简化导入路径。例如,如果你的组件结构如下:
src/ ├── components/ │ ├── Text/ │ │ ├── Text.tsx │ │ └── index.ts │ └── index.ts └── index.ts
在 Text.tsx 中导入其他组件时,可以使用以下路径:
import Text from 'atoms/Text/Text'; // 假设 atoms 是 paths 中配置的别名
有时候,Rollup 或 TypeScript 的构建缓存可能会导致问题。尝试清理构建缓存并重新构建项目:
rm -rf dist # 删除 dist 目录 npm run build # 重新构建项目
通过以上步骤,你应该能够解决在使用 Rollup 构建组件库时遇到的组件内部引用问题。 关键在于正确配置 rollup.config.mjs 和 tsconfig.json 文件,并确保模块导入路径是正确的。 此外,清理构建缓存也是一个有用的技巧。 请记住,构建组件库是一个迭代的过程,可能需要多次尝试和调整配置才能达到最佳效果。
以上就是使用 Rollup 构建组件库时解决组件内部引用问题的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号