Basic Webpack 5 Project with CSS: Step-by-Step
In this guide, we'll walk through setting up a basic Webpack 5 project with added support for CSS. This will allow you to bundle both JavaScript and CSS into your project efficiently.
Step 1: Set Up Your Project Directory
Start by creating a new project directory and initializing a package.json
file.
Step 2: Install Webpack, Webpack CLI, and CSS Loader Packages
To use Webpack, you need to install both Webpack and the Webpack CLI. Additionally, we will need css-loader
and style-loader
to handle CSS files.
Run the following command to install the necessary dependencies:
npm install webpack webpack-cli css-loader style-loader --save-dev
Step 3: Create the Project Structure
Create the following file structure for your project:
- src/index.js: This is where your JavaScript code goes.
- src/styles.css: This file will contain your CSS styles.
- dist/: This directory will hold the bundled output.
- webpack.config.js: The Webpack configuration file.
Step 4: Write Some JavaScript and CSS
Open src/index.js
and add a simple JavaScript function:
Next, add some CSS styles to src/styles.css
:
Step 5: Configure Webpack for JavaScript and CSS
In the root of your project, create the webpack.config.js
file and configure it to handle both JavaScript and CSS files:
- css-loader: This interprets
@import
andurl()
in CSS and resolves them. - style-loader: This injects CSS into the DOM.
Step 6: Add Scripts to package.json
In the "scripts"
section of your package.json
, add the following command to make it easier to build your project:
Now, you can bundle your project using:
Step 7: Bundle Your Project
Run the following command to bundle your JavaScript and CSS:
Webpack will create a bundled dist/bundle.js
file, which includes both the JavaScript and the CSS.
Step 8: Test the Output
Create an index.html
file inside the dist/
directory to test the output:
Open the dist/index.html
file in your browser. You should see a styled page with the heading "Welcome to Webpack 5 with CSS!" and a background color, confirming that both JavaScript and CSS are bundled correctly.
Conclusion
You’ve now set up a basic Webpack 5 project with CSS support. Webpack handles both JavaScript and CSS files, bundling them into a single output file. From here, you can expand your configuration to support more features like image loading, SCSS, or TypeScript.