How to bundle local typescript files into main bundle using Rollup

Viewed 2937

I am trying to create an npm module that can be used in the browser.

I'm using typescript and rollup.

My tsconfig.json is:

{
  "compilerOptions": {
    "module": "CommonJS",
    "outDir": "lib",
    "strict": true,
    "rootDir": "src"
  }
}

and my rollup.config.js is:

import typescript from "@rollup/plugin-typescript";

export default {
  input: "src/index.ts",
  output: {
    dir: "lib",
    format: "iife",
  },
  plugins: [typescript()],
};

Inside src/index.ts I have the following:

// src/index.ts
import log from './log'

const myFn = () => {
 ...myFn code
}

My issue is that in the bundle, I get the following:

// lib/index.js bundle
var log_1 = require("./log");

When I actually want to bundle the log file inside the main lib/index.js.

How can I do this with Typescript and rollup?

Note: I have tried to add outFile (ts docs) but that is not supported by "@rollup/plugin-typescript".

Do I have to do the tsc compile myself and then the rollup bundle?

1 Answers

Rollup requires the TypeScript compiler to generate ES Modules in order to properly bundle your code. You'll need to change the module format to "ESNext" instead of "CommonJS" in your tsconfig.json or change the @rollup/plugin-typescript configuration in your Rollup config:

typescript({ module: "ESNext" })

As of rollup/plugins#788, you will get a warning if this is not configured correctly.

@rollup/plugin-typescript: Rollup requires that TypeScript produces ES Modules. Unfortunately your configuration specifies a "module" other than "esnext". Unless you know what you're doing, please change "module" to "esnext" in the target tsconfig.json file or plugin options.

Related