Build your own library with rollup.js and TypeScript

  1. Initialize your project
  2. Add TypeScript support

Initialize your project

First of all, create a directory for your project then initialize with the npm command:

1
2
3
mkdir myTools
cd myTools
npm init -y

Next install rollup:

1
npm install rollup -D

Now create a folder for your source files, such as modules, then create the entry file index.js in it.

After that create rollup.config.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
export default {
input: "modules/index.js",
output: [
{
file: "lib/bundle.cjs.js",
format: "cjs",
},
{
file: "lib/bundle.esm.js",
format: "es",
},
],
};

Then add a command to your package.json file in order to run it more conveniently:

1
2
3
4
5
{
"scripts": {
"build": "rollup --config"
},
}

The next time you run the npm run build command, files will be generated in the lib directory.

Add TypeScript support

First, we need to install npm packages:

1
npm install typescript rollup-plugin-typescript2 tslib -D

Edit rollup.config.js file to use the TypeScript plugin:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import typescript from "rollup-plugin-typescript";
export default {
input: "modules/index.ts",
output: [
{
file: "lib/bundle.cjs.js",
format: "cjs",
},
{
file: "lib/bundle.esm.js",
format: "es",
},
],
plugins: [
typescript({
exclude: "node_modules/**",
typescript: require("typescript"),
}),
],
};

It is time to change the input value to your new entry file, such as modules/index.ts.