Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rollup + Typescript output JS file per component

I'm creating a reusable component library with React, TypeScript and Rollup.

Bundling this library into a single output file index.js works great. But, there are no .js output files generated for my individual components.

However, I'm trying to ensure I can use specific imports in my TypeScript projects.

E.g: import { ComponentA } from "my-components/lib/ComponentA;

This would then ensure my other components are not included when bundling my project afterwards.

So my question is: how can I configure Rollup so that all components are output as well into separate component output files?

My file structure looks like:

src
│ index.ts
└─components
  │ index.ts
  ├─ComponentA
  │   index.ts
  │   ComponentA.tsx
  └─ComponentB
      index.ts
      ComponentB.tsx

My rollup config is:

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"]
      }
    })
  ]
};

Which outputs to:

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

What I want to achieve is that in the output (lib) folder there are for example also ComponentA.js and ComponentB.js files.

like image 437
Nsevens Avatar asked Feb 28 '20 09:02

Nsevens


Video Answer


1 Answers

try adding flag preserveModule

export default {
  ...
  preserveModules: true,
  ...
}

It should work, a demonstration repo for this: https://github.com/daleyjem/rollup-preserve-modules

like image 156
Phạm Huy Phát Avatar answered Oct 17 '22 04:10

Phạm Huy Phát