Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Execute npx commands with $npm_ Environment Variables


    We will incorporate npm specific environment variables when executing various npx commands. In our example, we will transpile code to a folder name that matches the version of the current package.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Instructor: Let's create a folder, npx-env, and create a package.json file. If we run npm run env, you'll see that there are tons of environment variables that NPM makes available to us when running NPM scripts.

    Upon further investigation, we could grep those that start with npm_, and we'll find that there's a lot of information from inside our package.json represented as environment variables. What if we wanted to leverage those environment variables while using NPX?

    Let's try that, but first, we'll set up an environment to play around with. Here, we'll install Babel CLI, babel-preset-env, and babel-plugin-transform-object-rest-spread, using Bash brace expansion. We'll make them dev dependencies with the -D flag, and we'll pass -s to keep the logging silent.

    Now, we'll leverage the preset plugin by adding them to a Babel RC file. Then we'll add a Javascript file that takes an object with properties one and two, and then spreads it in a new object, with the three property.

    Using NPX to run our local installation of Babel, we'll ask it to transpile our code to the lib folder, which works just fine. However, what if we wanted to experiment, and have our output folder be prepended with the version of the package?

    What if we could use the environment variable $npm_package_version? Well, it didn't work. The output still went to lib/index.js. Let's try that again. However, this time, let's pass the -c flag to NPX, that will execute our command in an npm run script-like environment, meaning that it will have access to all the environment variables that we saw earlier.

    Sure enough, now our output file gets put into a lib/1.00folder. Now, since we feel good about our new command, we can open up our package.json, and make it an official NPM script, where it also has access to all those environment variables.

    We'll call it build, and we'll put the same command that we were just playing around with earlier. Now, we could come back and execute our new script with npm run build.