How to pass env variable to rollup.config.js via npm cli?

Viewed 11729

I have a scripts folder in which many individual scripts inside seperate folder, I would like to build each separately via passing the script name as parameter.

I have set up rollup in package.json like "watch": "rollup --watch --config rollup.config.js"

I would like to pass parameter from cli like npm run watch script_name=abc_script

It can be accessible in rollup.config.js via process.argv

But getting this error

rollup v1.23.1 bundles abc_script → dist/bundle.js [!] Error: Could not resolve entry module

Everything seems fine without npm cli parameter.

Rollup have --environment variable but it's bit long to use npm run watch -- --environment script:script_name

Is there any way to shorten this?

Thanks in advance.

4 Answers

While the following answer doesn't directly address OP's need (to pass variables in via command line), it does address their desire for brevity ("--environment variable but it's bit long to use")

Create a .env file in your project's root directory and fill it with VAR_NAME=value on each line

NODE_ENV=development
SECRET_KEY=ahuehueheueheueheu

DON'T COMMIT THAT FILE. Instead, add .env to your .gitignore.

Next install dotenv node package

npm i -D dotenv
yarn add -D dotenv

And finally put this at the very top of your rollup.config.js

import dotenv from 'dotenv';
dotenv.config();

You can pass arguments which will be caught by process.argv like this

npm run watch -- some_arg

In your program, you will get an array in process.argv in this the last value will be the value passed to the program.

Alternatively, you can pass environment variables to the command - it's much easier to process than command-line arguments.

Cli usage:

minify=on ./node_modules/.bin/rollup -c

package.json script:

{
  ...
  scripts: {
    ...
    "build-production": "minify=on rollup -c"
  }
}

rollup.config.js

const enableMinification = process.env.minify === 'on'

npm run watch -- --environment script=script_name worked for me, So I can access script_name via process.env in rollup config

Related