rollup / rollup-plugin-commonjs

This module has moved and is now available at @rollup/plugin-commonjs / https://github.com/rollup/plugins/blob/master/packages/commonjs
MIT License
502 stars 126 forks source link

cannot work with typescript plugin to bundle commonjs modules #377

Closed ryancat closed 5 years ago

ryancat commented 5 years ago

This plugin is not bundling commonjs module anymore if I have typescript code that tries to import a commonjs module.

declare function require(path: string): any;
const util = require('./util_es5');

Here is the config:

import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
import sourceMaps from 'rollup-plugin-sourcemaps'
import camelCase from 'lodash.camelcase'
import typescript from 'rollup-plugin-typescript2'
import json from 'rollup-plugin-json'

const pkg = require('./package.json')

const libraryName = 'test-lib'

export default {
  input: `src/${libraryName}.ts`,
  output: [
    { file: pkg.main, name: camelCase(libraryName), format: 'umd', sourcemap: true },
    { file: pkg.module, format: 'es', sourcemap: true },
  ],
  // Indicate here external modules you don't wanna include in your bundle (i.e.: 'lodash')
  external: [],
  watch: {
    include: 'src/**',
  },
  plugins: [
    // Allow json resolution
    json(),
    // Compile TypeScript files
    typescript({ useTsconfigDeclarationDir: true }),
    // Allow bundling cjs modules (unlike webpack, rollup doesn't understand cjs)
    commonjs(),
    // Allow node_modules resolution, so you can use 'external' to control
    // which external modules to include in the bundle
    // https://github.com/rollup/rollup-plugin-node-resolve#usage
    resolve(),

    // Resolve source maps to the original source
    sourceMaps(),
  ],
}

The output simply includes var util = require('./util_es5');, which will causing errors as util_es5.js is not in the dist folder.

bterlson commented 5 years ago

Mixing require with ESMs in TypeScript is a recipe for confusion and should be avoided. Rollup doesn't know anything about require being a thing as far as I know. I believe if you used dynamic import (import('./util_es5'), note this returns a promise) or ESM import (import * as util from "util") things should work properly. Feel free to re-open if this is not the case!