"Experienced Lead Developer oriented towards problem-solving and analyzing impacts, both technically and functionally, Enjoy's working with web technologies with a strong focus on quality code and robust system architecture."
HomeBlogWeb DevelopmentAn Introduction to Package JSON Scripts in Node.js
If you have ever had a face-off with a modern-stack JavaScript project or interacted with Node.js projects, you have certainly met the package.json file. Package.json is considered the manifest for your project, being a storefront of information about applications, modules, packages, and more. Though it is not just a central repository of tool configuration, it is also where npm stores the names and versions of all the installed packages. It has the power to automate many things, therefore, it is a good idea to grasp the commonly found and most crucial properties of a package.json file to use it effectively in a Node.js Project. One of the best ways to learn about Node effectively is to enroll in the Node.js tutorial and projects course.
Most Automations and unrelated actions can be boiled down to the scripts section of the package.json file.
Ever wondered what scripts are? What are they used for? What should we know about it, and what cool things can we do with it? If yes, let me give you a kickstart introduction to effectively using package.json Scripts with Node.js and npm.
An npm script is a convenient way to bundle common shell commands like a set of built-in and custom scripts for your project. They are typically terminal commands or a string of terminal commands that help automate repetitive tasks.
In short, NPM scripts are terminal commands that perform a set of actions.
In a project, scripts are stored in a section of the package.json file, which means they are shared amongst everyone using the codebase, ensuring that everyone is using the same command with similar flags.
Their purpose is to provide an effortless way to execute repetitive tasks, like:
These scripts can be used effortlessly in CI/CD pipeline to simplify tasks like building and generating test reports.
Using the NPM (Node Package Manager) scripts is also simple. To define an NPM script, set its name and write the script under the ‘scripts’ property of your package.json file:
To execute your Script, use the ‘npm run <NAME-OF-YOUR-SCRIPT>’ command. Some predefined aliases convert to npm run, like npm test or npm start, you can use them interchangeably.
Maintaining commands you run regularly as an npm script is common, like starting your application, linting, building production apps, etc.
A simple example for an npm script would be:
1. "scripts": { 2. "scss": "node-sass --output-style compressed -o dist/css src/scss" 3. } 4. 5. 6. Terminal Command to run the Script npm run scss …… run scss ……
Get a deeper understanding of the Node.is file system module.
Understanding how the package.json file works helps us manage and maintain it better.
As the name suggests, it is primarily a JSON file, so it needs to be a valid JSON. This means that any missing commas, unclosed quotation marks, or other formatting errors will prevent npm from interacting with it.
It is recommended that you use the npm CLI (Command Line Interface) to update and manage your package to avoid accidental errors and ease the process of managing your dependencies.
Always use `npm init` to initialize your package.json file, as it will ensure you generate a valid one.
Dependencies are best managed using different script commands like ‘npm install,’ npm uninstall, and npm update, so the package.json and node_modules/ folder are kept in sync.
Manually listing a dependency in the package file does not immediately reflect the state of our node_modules/ folder as our package.json file only records dependencies, and our node_modules/ folder is where the actual code for dependencies is installed. Therefore, it is needed that you run ‘npm install’ before the dependency is installed in your project.
That is why it is easier to use npm to help manage dependencies. It updates both the package file and node_modules folder together.
That said, even though it is not suggested, you can always edit your package file manually in your code editor and then make changes.
Various commands and scripts you want to be exposed can be specified here, and to discover all the available scripts, you can use the `npm run` command
Several built-in scripts are present in a Package.json file in addition to their pre-set life cycle events and arbitrary scripts. Let us look into some of them below.
If you are a beginner and want more information, you can go for a full-stack certification.
Let us begin with understanding what npm does when you run a script.
Number one on its checklist is to check the package.json file to see if you have defined a value for that script. If a value matching the script tag is found, it then checks for two other versions of the same script, that is, a ‘pre’ version and a ‘post’ version.
These scripts can be handy for many scenarios like the commands that need to be run before or after a set of actions performed in a project.
If either of these scripts is found, it will run them as the specified script.
A good example would be a command for deleting test logs before running the tests and running a linter afterward.
The creation of "pre" or "post" scripts is easy, these scripts can be defined in the "scripts" section with a matching name and adding "pre" or "post" to the beginning of them.
Let us take an example of such a script
npm run prepare should do the following
There are respectively pre- and post-hooks for a lot of commands. This comes in very handy to manage the life cycle of your application.
Life Cycle Scripts can be considered special scripts that happen only in certain situations. These scripts work in addition to the pre<event>, post<event>, and <event> scripts.
Let us suppose if this is what npm was to find in our package.json file, it will run the scripts in the order prestart, start, then poststart. All we would be doing to trigger this is typing `npm start` in the command line.
These kinds of scripts are beneficial for various situations where something is needed to happen immediately before or immediately after a primary action.
If we set up our scripts properly, simply running the command npm start will handle all our needs in the proper order.
The same behavior also applies to built-in commands. You can read more about those lifecycle scripts in the npm docs.
In some cases, there can be a need to get some extra juice out of your NPM scripts, in these cases, you can pass options to the command you are using in your npm script by adding a -- --flag like in the example below.
Let us see a few examples:
{ "scripts": { "lint": "eslint .", "test": "jest ./test", } }
If I wanted to run only the tests that changed, the command would be like this:
> npm run test -- --onlyChanged
And if you wanted to run the linter and save the output in a file, you could execute the following command:
> npm run lint -- --output-file lint-result.txt
User
When npm runs with root privileges, scripts are always run with the effective uid and gid of the working directory owner. To overcome this, you should set the unsafe-perm flag to run scripts with root privileges.
Environment
Scripts run in different environments where many pieces of information are made available regarding the setup of npm and the current state of the process.
Exit
Scripts are run by passing the line as a script argument to sh, and if it exits with a code other than 0, then this aborts the process.
Note that these script files do not have to be Node.js or JavaScript programs. They only must be some sort of executable file.
Looking to enhance your coding skills? Dive into the world of Python with our online python certification course. Unleash your potential and become a Python pro today!
Checking out this concise introduction to the principles around npm scripts should help you in your development workflow and make it easier to evaluate the scripts you come across. Hopefully, you will revisit this post when you begin developing your own scripts.
If you have any further questions, I recommend you look through the FAQs below or check out npm's well-written documentation, starting with the npm CLI docs. A Better set of resources can be found at KnowledgeHut’s Node.js tutorial and projects course.
For next steps, check out our blog posts about how to check installed npm package version in node.js.
An npm script is a convenient way to bundle common shell commands like a set of built-in and custom scripts for your project. They are typically terminal commands or a string of terminal commands that help automate repetitive tasks.
In short, NPM scripts are terminal commands that perform a set of actions.
In a project, Scripts are stored in a section of the package.json file and are defined as an object where the Key is the command name used on the terminal, and the value is the command we want to run.
To execute your Script, use the npm run <NAME-OF-YOUR-SCRIPT> command.
e.g.: npm run test or npm start
A package.json file contains metadata about the project and the functional dependencies required by the application.
package.lock.json is created for locking the dependency with the version installed. It will install the precise latest version of that package in your application and save it in package.json.
Without package.lock.json, there can be differences in installed versions in different environments. Package.lock.json is created and used to overcome this problem and have the same results in every environment.
Always use `npm init` to initialize your package.json file, as it will ensure you generate a valid one.
Name | Date | Fee | Know more |
---|