Skip to content

How to use with rollup

Ye-hyoung Kang edited this page May 11, 2021 · 10 revisions

Install command-line-args.

$ npm install command-line-args

Create bundle without rollup plugins

Example script (save it as index.mjs). This example loads the command-line-args ESM distribution.

import commandLineArgs from './node_modules/command-line-args/dist/index.mjs'

const optionDefinitions = [
  { name: 'verbose', type: Boolean }
]
const options = commandLineArgs(optionDefinitions)
console.log(options)

Example rollup config creating an ESM bundle (save as rollup.config.js).

export default {
  input: 'index.mjs',
  output: {
    file: 'dist.js',
    format: 'cjs'
  }
}

Run rollup to create the bundle.

$ rollup -c rollup.config.js

Run the bundle.

$ node dist.js --verbose
{ verbose: true }

Create bundle using rollup plugins

You can also load command-line-args as a CommonJS module this way:

import commandLineArgs from 'command-line-args'

Rollup config required to achieve this.

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

export default {
  input: 'index.mjs',
  output: {
    file: 'dist.js',
    format: 'cjs'
  },
  plugins: [
    resolve(),
    commonjs()
  ]
}