React+TypeScript+Rollup组件库实现子路径模块化导出方法问询
实现组件库的子路径模块化导出
要实现类似Redux的子路径导入方式,需要调整项目结构、Rollup配置和package.json的核心导出规则,具体步骤如下:
1. 调整项目结构
先梳理清晰的模块化目录结构,每个子模块单独维护并导出内容:
my-library/ ├── src/ │ ├── components/ │ │ ├── Component1.tsx │ │ ├── Component2.tsx │ │ └── index.ts # 导出当前子模块内容 │ ├── styles/ │ │ ├── style1.ts │ │ ├── style2.ts │ │ └── index.ts │ ├── hooks/ │ │ ├── useHook1.ts │ │ ├── useHook2.ts │ │ └── index.ts │ └── index.ts # 主模块入口(可选,保留从根路径导入的方式) ├── rollup.config.js ├── package.json └── tsconfig.json
每个子文件夹的index.ts负责导出内部内容,例如src/components/index.ts:
export { default as Component1 } from './Component1'; export { default as Component2 } from './Component2';
根目录src/index.ts可选择性导出主模块内容:
export * from './components';
2. 配置TypeScript支持
在tsconfig.json中开启类型声明,并配置路径映射让TS识别子路径:
{ "compilerOptions": { "baseUrl": ".", "paths": { "my-library": ["src/index.ts"], "my-library/styles": ["src/styles/index.ts"], "my-library/hooks": ["src/hooks/index.ts"] }, "declaration": true, "declarationDir": "dist", "outDir": "dist", // 其他原有配置 } }
3. 配置Rollup多入口打包
修改rollup.config.js,为每个子模块单独配置打包入口,确保输出对应目录:
import { defineConfig } from 'rollup'; import typescript from '@rollup/plugin-typescript'; import resolve from '@rollup/plugin-node-resolve'; import commonjs from '@rollup/plugin-commonjs'; export default defineConfig([ // 主模块打包 { input: 'src/index.ts', output: [ { file: 'dist/index.js', format: 'esm', sourcemap: true }, { file: 'dist/index.cjs', format: 'cjs', sourcemap: true } ], plugins: [resolve(), commonjs(), typescript({ tsconfig: './tsconfig.json' })] }, // styles子模块打包 { input: 'src/styles/index.ts', output: [ { file: 'dist/styles/index.js', format: 'esm', sourcemap: true }, { file: 'dist/styles/index.cjs', format: 'cjs', sourcemap: true } ], plugins: [resolve(), commonjs(), typescript({ tsconfig: './tsconfig.json' })] }, // hooks子模块打包 { input: 'src/hooks/index.ts', output: [ { file: 'dist/hooks/index.js', format: 'esm', sourcemap: true }, { file: 'dist/hooks/index.cjs', format: 'cjs', sourcemap: true } ], plugins: [resolve(), commonjs(), typescript({ tsconfig: './tsconfig.json' })] } ]);
4. 配置package.json的exports字段(核心)
这是让Node.js和打包工具识别子路径的关键,在package.json中添加:
{ "name": "my-library", "version": "1.0.0", "type": "module", "main": "dist/index.cjs", "module": "dist/index.js", "types": "dist/index.d.ts", "exports": { ".": { "import": "./dist/index.js", "require": "./dist/index.cjs", "types": "./dist/index.d.ts" }, "./styles": { "import": "./dist/styles/index.js", "require": "./dist/styles/index.cjs", "types": "./dist/styles/index.d.ts" }, "./hooks": { "import": "./dist/hooks/index.js", "require": "./dist/hooks/index.cjs", "types": "./dist/hooks/index.d.ts" } }, // 其他原有配置(scripts、dependencies等) }
5. 测试导入
完成上述配置后,即可在项目中按预期方式导入:
import { Component1, Component2 } from 'my-library'; import { style1, style2 } from 'my-library/styles'; import { hook1, hook2 } from 'my-library/hooks';
内容的提问来源于stack exchange,提问作者Cleber Dias
相关产品推荐
相关产品推荐

