In this exercise, we will set up a Webpack project starting from an empty folder.
Set Up package.json
Webpack is a Node package. To use Node packages, we need a package.json which holds important project metadata about any Node project. We can initialize a Node project using npm init
in the terminal to make a package.json file. We can use the -y
flag to use the default values for the metadata fields:
npm init -y
Install Webpack and Webpack CLI
We need two packages, webpack
and webpack-cli
, to build our Webpack project with the command line. webpack
contains the main functionality, but webpack-cli
allows command-line access to Webpack. We want these tools to be developer dependencies because they will not be used when the final product is running. We use npm install
and the --save-dev
flag to save packages as developer dependencies.
npm install --save-dev webpack webpack-cli
package.json will list these packages under devDependencies
for a local project.
Make an entry point
A Webpack project requires an entry point where it will find the main file to bundle. Webpack will throw a long error indicating a problem with main
if there are no files at the entry point. The default Webpack entry point is index.js in a src folder, although this can be changed. If we want to use the default entry point, we should make an src folder with an index.js inside of it.
Define the Build Command
A build
command is often defined in the scripts
section of package.json for running Webpack. You can find more information on the scripts section here. Using a build
command makes the way we build the project independent of what build tools we use. We define the build command like so:
"scripts": { "build": "webpack --watch", },
The webpack
of the command just runs Webpack, --watch
tells Webpack to automatically look for updates to our file and rebuild if any changes occur. This will be important when we preview our site.
We run the build command in the terminal with:
npm run build
When we’ve set up the package.json, entry point, and build command, Webpack is ready to go!
Let’s practice setting up Webpack!
Instructions
Let’s get started by initializing our package.json with npm
.
Next, let’s define our build command in the package.json.
Find and open package.json in the file explorer, then define the command.
Note that the required packages have already been installed.
Click the “Run” button when done.
We are almost ready to build! Make the required entry point by creating a folder called src. Inside, create an empty file called index.js. Click the “Run” button when you’re done.
Run the build
command and make sure our project is off to a good start!
Our project should compile with a warning indicating the mode isn’t set. We will fix that when we create a config file in a future exercise.