我正在使用 React、TypeScript 和 Rollup 创建一个可重用的组件库。
将此库捆绑到单个输出文件中 index.js
效果很好。但是,没有.js
为我的 生成的输出文件单个组件 .
但是,我正在努力确保我可以在我的 TypeScript 项目中使用特定的导入。
例如:import { ComponentA } from "my-components/lib/ComponentA
;
这将确保我的其他组件在之后捆绑我的项目时不包括在内。
所以我的问题是:如何配置 Rollup 以便所有组件也输出到单独的组件输出文件中?
我的文件结构如下:
src
│ index.ts
└─components
│ index.ts
├─ComponentA
│ index.ts
│ ComponentA.tsx
└─ComponentB
index.ts
ComponentB.tsx
我的汇总配置是:
import commonjs from "@rollup/plugin-commonjs";
import resolve from "@rollup/plugin-node-resolve";
import external from "rollup-plugin-peer-deps-external";
import typescript from "rollup-plugin-typescript2";
export default {
input: "src/index.ts",
output: [
{
file: pkg.main,
format: "cjs",
exports: "named",
sourcemap: true
},
{
file: pkg.module,
format: "es",
exports: "named",
sourcemap: true
}
],
plugins: [
external(),
resolve({
browser: true
}),
typescript({
rollupCommonJSResolveHack: true,
exclude: "**/__tests__/**",
clean: true
}),
commonjs({
include: ["node_modules/**"],
exclude: ["**/*.stories.js"],
namedExports: {
"node_modules/react/react.js": [
"Children",
"Component",
"PropTypes",
"createElement"
],
"node_modules/react-dom/index.js": ["render"]
}
})
]
};
输出到:
lib
│ index.d.ts
│ index.es.js
│ index.es.js.map
│ index.js
│ index.js.map
└─components
│ index.d.ts
├─ComponentA
│ index.d.ts
│ ComponentA.d.ts
└─ComponentB
index.d.ts
ComponentB.d.ts
我想达到什么例如,在输出(lib)文件夹中还有
ComponentA.js
和 ComponentB.js
文件。
最佳答案
尝试添加标志 preserveModule
export default {
...
preserveModules: true,
...
}
它应该可以工作,这是一个演示仓库:https://github.com/daleyjem/rollup-preserve-modules
关于typescript - 每个组件的 Rollup + Typescript 输出 JS 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60448485/