NPM Scripts Integration
NPM allows us to define custom scripts in the package.json file. These can then be execute tasks using the NPM CLI.
We rely on these scripts to manage most of our project tasks and webpack fits in as well.
The scripts are defined in the scripts property of the package.json file. For example:
...
scripts: {
"clean": "rimraf dist",
"prebuild": "npm run clean",
"build": "NODE_ENV=production webpack",
}
...
NPM allows pre and post task binding by prepending the word pre or post respectively to the task name. Here, our prebuild task is executed before our build task.
We can run an NPM script from inside another NPM script.
To invoke the build script we run the command npm run build:
- The
prebuildtask executes. - The
prebuildtask runs thecleantask, which executes therimraf distcommand. rimraf(an NPM package) recursively deletes everything inside a specified folder.- The
buildtask is executed. This sets theNODE_ENVenvironment variable toproductionand starts the webpack bundling process. - Webpack generates bundles based on the
webpack.config.jsavailable in the project root folder.