How to include both import and require statements in the bundle using rollup

Viewed 4448

When I use only const Example1 = require('./example1.js) statement then code inside example1.js file is getting included in the bundle. And if I use only import Example2 from './example2.js' then also code inside example2.js is getting included in the bundle. But if I use both the statements only import is working and require is not working.

I am using rollup for bundling.

My rollup configuration looks like this

import babel from 'rollup-plugin-babel'
import commonjs from 'rollup-plugin-commonjs'
import external from 'rollup-plugin-peer-deps-external'
import postcss from 'rollup-plugin-postcss'
import resolve from 'rollup-plugin-node-resolve'
import url from 'rollup-plugin-url'
import svg from 'rollup-plugin-svg'
import json from 'rollup-plugin-json';
import { terser } from 'rollup-plugin-terser'

export default {
  input: 'src/sdk/test.js',
  output: [
    {
      file: "src/sdk/sdk.js",
      format: 'cjs'
    },
    {
      file: "src/sdk/sdk.es.js",
      format: 'es'
    },
    {
      file: "src/sdk/sdk.iife.js",
      format: 'iife'
    }
  ],
  plugins: [
    resolve({
      browser: true,
    }),
    commonjs(),
    external(),
    postcss({
      modules: true
    }),
    url({
      limit: 100 * 1024,
      emitFiles: false
    }),
    svg(),
    babel({
      exclude: 'node_modules/**',
      "plugins": ["@babel/plugin-proposal-class-properties"]
    }),
    terser(),
    json()
  ]
}
1 Answers

By default, rollup supports 'esm' modules as entry. If you like to include commonjs files in the project, you can include '@rollup/plugin-commonjs' into plugins field, it usually works.

Maybe the following config will help, I tried with very simple example:

commonjs({transformMixedEsModules:true})

transformMixedEsModules Instructs the plugin whether or not to enable mixed module transformations. This is useful in scenarios with mixed ES and CommonJS modules. Set to true if it's known that require calls should be transformed, or false if the code contains env detection and the require should survive a transformation.

https://github.com/rollup/plugins/tree/master/packages/commonjs

Related