Search code examples
configurationcommonjsrollupjs

require is not defined using rollup


I have the following rollup.config.js:

import commonjs from 'rollup-plugin-commonjs';
import nodeResolve from 'rollup-plugin-node-resolve';

export default {
  input: 'input.js',
  output: {
    file: 'output.js',
    format: 'iife'
  },
  plugins: [
    nodeResolve(
      {
        jsnext: true,
        main: true
      }
    ),
    commonjs({ include: 'hello.js' })
  ]
}

I have the following input.js which requires hello.js:

var hello = require('./hello.js');

console.log(hello);

and hello.js is simply:

module.exports = 'hello';

I would like output.js to not include the require syntax and for it to be replaced it with the string 'hello'.

I instead still see the line var hello = require('./hello.js');

How can I replace this line with a rollup plugin? (I thought that is what the commonjs plugin was for).

Thanks in advance for the help!


Solution

  • Worked it out.

    The problem was with my input.js file.

    The plugin doesn't support require, but the plugin facilitates module.exports.

    Changing input.js to be:

    import x from './hello.js';
    
    console.log(x);
    

    worked.