Use package.json variables in npm scripts

Elijah Manor
InstructorElijah Manor

Share this video with your friends

Send Tweet
Published 5 years ago
Updated 3 years ago

In this lesson we will show that you can leverage values that you already have provided in your package.json file such as the name and version keys. You may want to use these in your npm scripts as you create folders and file names.

[00:02] MPM has package level variables you could use in your scripts such as name, version, etc. You could look at all of MPM's variables by running MPM run MB, and then we'll grab for just the ones that start with MPM_package.

[00:15] Then we'll pipe those to less. As you'll see, there's tons of variables and we could search for just the version which is the one we're about to use. Let's update our scripts so when we build it'll create a folder for our current version. We'll start with our prebuild script.

[00:33] Where we list the public folder we'll use the variable MPM package_version which in this case we'll resolve to public/01.0Note the dollar sign signifies that we're referencing a variable. Then in our build:HTML we'll also append the dollar sign MPM package_version. Let's go ahead and save that.

[00:57] Then we'll update our build:CSS script and our build:JSscript. Now if we save our file and go back to the terminal we could run MPM run build and we'll see the prebuild clean up the public folder, and each of the build:HTML build:CSS and build:JSscripts output their contents to the public/01.0folder. And that's it.

Victor
Victor
~ 5 years ago

On windows, variables are used with %:

%npm_package_version%
Elijah Manor
Elijah Manorinstructor
~ 5 years ago

Very true. There are many things that need to be address when you want npm scripts to run cross-environment. I cover several of those concepts in lesson 16. My intent was to start simple and then talk about challenges as they came along.

Alexander Hofstede
Alexander Hofstede
~ 5 years ago

Why are the files also in /public in the end there?

Elijah Manor
Elijah Manorinstructor
~ 4 years ago

Why are the files also in /public in the end there?

Those were left over from before I added the logic to make the folders :) Great question