As a JavaScript developer, spending too much time on mundane coding tasks can be frustrating. Thankfully, Node.js offers many useful packages that can boost your productivity and make development easier. In this comprehensive guide, we‘ll explore 19 must-know Node.js packages that no JavaScript developer should be without.
ESLint
ESLint is a powerful linting utility for JavaScript. It parses your code to detect problematic patterns and enforces consistent style rules. ESLint is highly customizable through plugins and configurations.
To get started, install ESLint globally:
npm install -g eslint
After installing, run ESLint on your project to detect issues:
eslint your-js-files.js
ESLint will flag potential bugs, stylistic errors, unused variables, and more. Many problems can be automatically fixed with:
eslint your-js-files.js --fix
Overall, ESLint saves developers hours of time by eliminating manual code reviews and enforcing one consistent coding style.
Prettier
Prettier is a code formatter that automatically tidies up your code for consistent style and improved readability. For example:
foo(reallyLongArg(), omgSoManyParameters(), IShouldRefactorThis(), isThereSeriouslyAnotherOne());
Becomes:
foo(
reallyLongArg(),
omgSoManyParameters(),
IShouldRefactorThis(),
isThereSeriouslyAnotherOne()
);
Install Prettier globally:
npm install -g prettier
Then format code by running:
prettier file.js --write
Prettier supports many languages beyond JavaScript and integrates nicely with most editors. Overall, it‘s a huge time-saver that enforces clean code.
cross-env
The cross-env package makes it easy to handle setting environment variables across platforms. For example:
cross-env NODE_ENV=production webpack
This will set NODE_ENV to production for the webpack command regardless of the host OS. No more issues with setting env vars on Windows!
cross-env is useful for configuring build scripts, test commands, and anything else needing consistent environment variables.
nodemon
nodemon automatically restarts your Node.js application when files change. This saves developers from manually restarting during active development.
Install nodemon globally like so:
npm install -g nodemon
Then simply run your app with nodemon instead of node:
nodemon app.js
Now nodemon will watch for any changes and restart the server. No more having to manually restart!
PM2
PM2 is a production process manager for Node.js. It helps manage and scale Node apps by load balancing, monitoring, and clustering processes.
Key features include:
- Built-in load balancer
- Automatic app restarts on crashes
- Easy log management
- Deployment workflow
- And more…
Install PM2 globally:
npm install pm2 -g
Some useful commands include:
pm2 start app.js // Start app
pm2 monit // Monitor status
pm2 logs // View logs
pm2 stop app // Stop app
For production Node.js apps, PM2 is a must-have for process management.
Webpack
Webpack is a module bundler that takes your assets (JavaScript, CSS, images, etc) and bundles them into optimized static files ready for production.
Some key benefits include:
- Bundles application dependencies
- Minifies and optimizes assets
- Can split code into "chunks"
- Supports many plugins
- Integrates with Hot Module Replacement
To get started, install Webpack locally:
npm install webpack webpack-cli --save-dev
Then configure it via a webpack.config.js file. Run builds through the webpack command.
Webpack can seem complex at first but is invaluable for bundling front-end apps.
Parcel
Parcel is a blazing fast web application bundler that requires zero configuration. It‘s a simpler alternative to Webpack.
Install Parcel through npm:
npm install -g parcel-bundler
Parcel automaticallybundles assets referenced from an entry point, such as index.html. It needs no config by default.
Some advantages over Webpack:
- Faster performance
- Requires zero configuration
- Automatically transforms files
- Easy image optimization
- Bundles CSS assets referenced from JS
Parcel is perfect for simpler apps and fast prototyping.
Babel
Babel is a toolchain that converts ECMAScript 2015+ syntax into backwards compatible JavaScript. This allows developers to use the latest and greatest JavaScript features while targeting older browsers.
First, install the Babel CLI and a preset:
npm install -D @babel/core @babel/cli @babel/preset-env
Create a .babelrc file to define your presets and plugins.
Then run Babel:
./node_modules/.bin/babel script.js --out-file script-compiled.js
This will transpile script.js containing modern syntax into script-compiled.js for broader compatibility.
Babel is invaluable for using modern JavaScript while supporting legacy browsers.
ESLint + Prettier + Lint-Staged
One optimal setup for JavaScript projects is using ESLint, Prettier, and Husky together like so:
- Use ESLint to catch code issues
- Use Prettier to auto-format styling
- Use Husky to run linting/formatting pre-commit
First install everything:
npm install -D eslint prettier husky lint-staged
Add scripts for formatting and linting:
{
"scripts": {
"format": "prettier --write .",
"lint": "eslint ."
}
}
Configure ESLint and Prettier.
Then in package.json:
{
"lint-staged": {
"*.js": [
"npm run format",
"npm run lint"
]
}
}
This automatically lints and formats on commit!
This combo allows enforcing code style while eliminating bugs before they reach your codebase.
StandardJS
StandardJS is a JavaScript style guide/linter with far less configuration than ESLint. It enforces strict style rules out of the box.
Install it globally:
npm install standard --global
Run StandardJS to lint all your JS:
standard
It will flag stylistic issues and code irregularities. You can also run StandardJS to auto-fix issues when possible with:
standard --fix
StandardJS simplifies enforcing consistent code style immensely. However, it offers less customization than ESLint.
commitizen
commitizen is a tool to help craft standardized commit messages following the Conventional Commits spec.
Install it globally with:
npm install -g commitizen
Then in your project run:
git cz
Instead of git commit. This will guide you through creating a formatted commit message.
Well-formatted commit messages accelerate review and improve change logs. commitizen makes adhering to standards painless.
rimraf
rimraf provides a cross-platform rm -rf to delete files and directories. The built-in fs.rmdir() and fs.unlink() in Node.js have limitations that rimraf overcomes.
Install rimraf locally:
npm install rimraf --save
Then import and use it:
const rimraf = require("rimraf");
rimraf("my-directory", error => {
// Directory removed
});
rimraf makes reliably deleting files on any platform a breeze.
node-fetch
The node-fetch module brings the modern fetch API to Node.js for making HTTP requests.
Install it:
npm install node-fetch
node-fetch provides a clean, promise-based syntax for requests:
const fetch = require("node-fetch");
const response = await fetch(url);
const json = await response.json();
This is way cleaner than using callbacks!
node-fetch makes HTTP calls easy without bulky libraries like Axios.
PurgeCSS
PurgeCSS analyzes your code to detect which CSS selectors are actually used. It then removes unused CSS to optimize your bundled CSS assets.
Install via npm:
npm install @fullhuman/postcss-purgecss --save-dev
Configure PurgeCSS to run on your CSS during builds.
This eliminates unused CSS that bloats file sizes. PurgeCSS and PostCSS are a powerful combo.
Husky + lint-staged
Husky allows running scripts at certain Git hook points like pre-commit and post-merge.
Combining it with lint-staged enables running tasks like linting and testing on Git staged files.
Install both tools:
npm install husky lint-staged --save-dev
Configure tasks to run on pre-commit:
{
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.js": ["eslint --fix", "git add"]
}
}
This workflow helps prevent bugs and issues before they ever touch the codebase!
Ava
Ava is a JavaScript test runner focused on simplicity and speed. Key features:
- Parallel test running
- Simple assert APIs
- Async test support
- Snapshot testing
- No configuration required
- Process isolation
- And more…
Install:
npm install --save-dev ava
Tests are written with:
import test from ‘ava‘;
test(‘foo‘, t => {
t.pass();
});
Ava is perfect for writing clean, robust JavaScript tests.
XO
XO is an opinionated linting and formatting toolkit. It enforces strict code style, similar to StandardJS.
Install XO:
npm install --save-dev xo
XO will lint your code for common issues. Format code with:
xo --fix
The beauty of XO is it avoids bikeshedding by providing a default set of opinionated rules. No .eslintrc needed!
However, it offers less customization than ESLint.
ShellJS
ShellJS provides Unix shell commands for Node.js. This allows running shell commands directly:
const shell = require(‘shelljs‘);
if (!shell.which(‘git‘)) {
shell.echo(‘Sorry, Git is not installed.‘);
shell.exit(1);
}
ShellJS includes cross-platform versions of utilities like cp, mv, mkdir, grep, sed, chmod, and more.
Install it via npm:
npm install --save shelljs
ShellJS makes executing shell commands in Node.js simple.
Immer
Immer is a tiny package that enables immutable state management using normal mutative code.
For example:
import { produce } from "immer"
const nextState = produce(baseState, draftState => {
// Change draftState however you like
})
This constructs the next immutable state while writing standard mutative code!
Immer utilizes JavaScript Proxies for behind-the-scenes immutable enforcement. It integrates nicely with Redux and React state management.
Overall, Immer makes immutable data easier to reason about.
dayjs
For date management, dayjs is a minimal JavaScript library that parses, validates, manipulates, and displays dates/times.
Install via npm:
npm install dayjs --save
Some examples:
dayjs().format(); // Formats date
dayjs().add(1, ‘day‘); // Mutate date
dayjs(‘2019-01-25‘).isValid(); // Validate
dayjs offers a cleaner date API with a smaller footprint than Moment.js.
Async
Async provides utilities for working with asynchronous JavaScript. It includes functions like map(), filter(), reduce(), and powerful control flow.
Install:
npm install --save async
This allows, for example:
async.map(files, fs.readFile, (err, contents) => {
// All files read
});
Async makes orchestrating promises, callbacks, and streams painless.
Lodash
Lodash is a utility library providing helpers for common programming tasks.
It includes utilities like:
getandsetfor accessing nested valuesuniqByandunionByfor arraysomitandpickfor objectsdebouncefor rate-limiting- And many more
Install via npm:
npm install lodash
Lodash should be considered essential for any sizable JavaScript project.
axios
axios is an HTTP client for making promise-based requests from Node and the browser.
Install via npm:
npm install axios
Make requests with:
const axios = require(‘axios‘);
axios.get(‘/users‘)
.then(response => {
console.log(response.data)
})
axios supports async/await, defaults globally, interceptors, and more. It makes HTTP calls simpler than using fetch().
Conclusion
These 19 packages are just a sampling of the many helpful libraries in the Node.js ecosystem. From linting to date handling to HTTP requests, these tools will accelerate your productivity as a JavaScript developer.
By leveraging packages like ESLint, Prettier, and Babel, you can write cleaner and more maintainable code. Webpack, Parcel, and other bundlers help optimize your apps for production. Powerful utilities like Lodash, Immer, and dayjs abstract away common programming tasks.
Approach these tools with a focus on simplifying development workflows. Avoid reaching for libraries before you need them, but do keep these handy packages in mind for tackling everyday JavaScript tasks.