Rollup bundle node_modules into app when using Typescript

Viewed 2318

I have a Typescript application. I want to bundle the dependencies inside node_modules into the resulting bundle. Here's what I've tried so far based on these posts (Does rollup bundle node_modules into bundle.js?, Does rollup bundle node_modules into bundle.js?).

Here's my rollup config and the simple file I've tried bundling:

import typescript from "@rollup/plugin-typescript";
import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import globals from "rollup-plugin-node-globals";
import builtins from "rollup-plugin-node-builtins";

export default {
  input: "src/test.ts",
  output: {
    dir: "dist/",
    format: "iife",
  },
  plugins: [
    resolve({jsnext: true}),
    commonjs({ include: ["src/test.ts", "node_modules/**"] }),
    // I need to polyfill some node stuff
    globals(),
    builtins(),
    typescript({ noEmitOnError: false, outDir: "dist/" }),
  ],
};

The file:

import * as obj from 'some-module'
console.log(obj)

How can I get dependencies in node_modules to be bundled into the final output when using rollup + typescript? I suspect the issue is that the Typescript plugin is outputting files which use require and rollup cannot recognize require.

2 Answers

In package.json, make sure the dependencies you want to include is registered in dependencies property not peerDependencies. Rollup will bundled them in the output then.

You need to configure TypeScript to output ES modules for it to work. Set module to "ESNext" in your tsconfig.json:

{
    "compilerOptions": {
      "module": "ESNext"
    }
}
Related