Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
The best Rollup config for TypeScript libraries

Features

🔥 Blazing fast builds
😇 CommonJS bundle
🌲 .mjs bundle
.d.ts bundle + type-checking
🧐 Source maps

Install

  1. Install pnpm or replace the pnpm i part with Yarn or NPM.
  1. Run this in your terminal:

    pnpm i esbuild rollup rollup-plugin-esbuild rollup-plugin-dts -D
    wget -O rollup.config.js https://gist.githubusercontent.com/aleclarson/9900ed2a9a3119d865286b218e14d226/raw/rollup.config.js
  2. Ensure your tsconfig.json contains these values:

    "compilerOptions": {
      "target": "esnext"
    }
  3. Ensure your package.json contains these values (and replace the my-lib part):

    "main": "dist/my-lib.js",
    "module": "dist/my-lib.mjs",
    "typings": "dist/my-lib.d.ts",
  4. Change the input: 'src/index.ts' line in rollup.config.js if needed.

  5. All done! Now do yarn rollup -c to build, or add this to your package.json:

    "scripts": {
      "build": "rollup -c"
    }
import dts from 'rollup-plugin-dts'
import esbuild from 'rollup-plugin-esbuild'
const name = require('./package.json').main.replace(/\.js$/, '')
const bundle = config => ({
...config,
input: 'src/index.ts',
external: id => !/^[./]/.test(id),
})
export default [
bundle({
plugins: [esbuild()],
output: [
{
file: `${name}.js`,
format: 'cjs',
sourcemap: true,
},
{
file: `${name}.mjs`,
format: 'es',
sourcemap: true,
},
],
}),
bundle({
plugins: [dts()],
output: {
file: `${name}.d.ts`,
format: 'es',
},
}),
]
@steve-taylor

This comment has been minimized.

Copy link

@steve-taylor steve-taylor commented Jun 25, 2021

Simple and it works. Thanks!

@danechitoaie

This comment has been minimized.

Copy link

@danechitoaie danechitoaie commented Aug 13, 2021

With what Node.js version does using "target": "esnext" makes it compatible? Will it generate Node.js 12 compatible code?

@danechitoaie

This comment has been minimized.

Copy link

@danechitoaie danechitoaie commented Aug 13, 2021

@TorbjornHoltmon Awesome! Thanks!

@JoshBowdenConcepts

This comment has been minimized.

Copy link

@JoshBowdenConcepts JoshBowdenConcepts commented Nov 23, 2021

I tried this with styled-components and it failed to grab the module. Is that supposed to be in a separate bundle?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment