Use custom config settings in your npm scripts

Elijah Manor
InstructorElijah Manor
Share this video with your friends

Social Share Links

Send Tweet

In addition to package.json level variables (such as name and version), you can have custom conf settings that can be used in your npm scripts. These config values can be overridden outside of the package.json by using the npm config set command if necessary.

Instructor: [00:01] NPM supports custom configuration parameters that you either sign in the package.json or on the command line. Let's create a port key with the value of 1337, which will be the port we'll use when starting up an HTTP server to run our website.

[00:18] At this point, I could go to the terminal and type npm run env for a list of NPM's variables. If I grep config_port, we'll see that NPM now has that as an environment variable for us to use. Now, let's go back to our package.json and add some server scripts.

[00:36] First, we'll create a server:create script, which will kick of an HTTP server. While we're thinking about it, let's install that on the command line. HTTP server, we'll install it as a dev dependency. Now, let's go back and tell HTTP server to host our public/$npm package version, and to use the port from our config section, which is NPM package config port.

[01:09] Our server launch script will open up the browser to the location of our hosted website. It's localhost:npm package config port. Now, let's create a generic server that'll run these two subscripts parallel.

[01:28] We'll say npm run all, and we'll say parallel. We'll say server:*. Finally, we'll create a post start script that'll run both our build and our server. Now, if we save that and go back to our terminal, we should be able to type npm start, which will start our main script, executing and gathering all of React's file size information.

[01:52] Then in post start, it'll build our HTML, CSS, and JavaScript assets. Then it'll kick off a server using the port that we requested, which is 1337. Sure enough, it pulled up the website with 1337. Now, let's cancel our server.

[02:08] You could also override the config value from the command line. If we typed npm config set, and then the name of our package, which is React File Size, with a colon, and saying port, we could override the value to 1338.

[02:23] Now, if we kick off npm run server, it'll kick up a server with port 1338, instead of the default 1337, which is our package.json file. Sure enough, it did. You could list NPM's configurations with npm config lists.

[02:40] If we pipe that to Grep and look for React, sure enough, we could find our variable. However, you may want to delete this override. You could do so by npm config delete react-file-size:port. Now, if we were to look in the list again, it wouldn't find it.