Friday, 3 February 2023

How to set up rollup config to allow for direct imports?

I have created a component library in React and am using rollup as my bundler.

My project directory looks like this:

src
├── assets
│   ├── fonts
│   └── icons
├── components
│   ├── Alert
│   │   ├── Alert.tsx
│   │   └── index.tsx
│   ├── Button
│   │   ├── Button.tsx
│   │   └── index.tsx
│   └── index.tsx
├── styles
├── utils
└── index.tsx

My package.json looks like this:

"files": [
  "dist"
],
"main": "dist/esm/index.js",
"module": "dist/esm/index.js",
"type": "module",
"exports": {
  ".": "./dist/esm/index.js",
  "./components": "./dist/esm/components",
  "./assets": "./dist/esm/assets",
  "./utils": "./dist/esm/utils"
},
"types": "dist/index.d.ts",

My rollup configuration looks like:

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 copy from "rollup-plugin-copy-assets";
import dts from 'rollup-plugin-dts';
import postcss from 'rollup-plugin-postcss';

import svgr from '@svgr/rollup';

import packageJson from './package.json' assert { type: "json" };

/**
 * @type {import('rollup').RollupOptions}
 */
const config = [
  {
    input: 'src/index.ts',
    output: [
      {
        file: packageJson.module,
        format: 'esm',
      },
    ],
    plugins: [
      copy({
        assets: [
          "src/assets",
        ]
      }),
      resolve(),
      commonjs(),
      typescript({
        tsconfig: './tsconfig.build.json',
        declaration: true,
        declarationDir: 'dist',
      }),
      postcss(),
      svgr({ exportType: 'named', jsxRuntime: 'automatic' }),
      terser(),
    ],
    external: ['react', 'react-dom', 'react-select', 'styled-components'],
  },
  {
    input: 'dist/esm/index.d.ts',
    output: [{ file: 'dist/index.d.ts', format: "esm" }],
    external: [/\.(css|less|scss)$/],
    plugins: [dts()],
  },
];

export default config;

Currently when I use the library, I have to import components like

import { components } from 'package-name';

But I would like to be able to import like

import Alert from 'package-name/components/Alert';

// or

import { Alert } from 'package-name/components';

How can I set up rollup/package.json to allow for this?



from How to set up rollup config to allow for direct imports?

No comments:

Post a Comment