installing the necessities:
npm init -y
npm i webpack webpack-cli webpack-dev-server
npm i @babel/cli @babel/core @babel/preset-env
npm i babel-loader css-loader style-loader
package.json file:
After installation, we would add scripts to run the webpack:
"scripts":{
“build” : “webpack watch”,
“dev-server”: “webpack serve --open”
}
folder structure:
> --dist/
> ----index.html
> --src/
> ----index.js
> ----style.css
Webpack takes the files in “src” as input and outputs a single minified file named ‘main.js’ inside the “dist” folder. We will see this once we run webpack.
wepack.config.js:
create a webpack.config.js file in the root of your project folder :
Running webpack
For running webpack we would have to give the following command in the terminal :
npm run dev-server
Now if we look at our folder structure, you would see a main.js file inside the “dist” folder:
> --dist
> ----bundle.js
> ----index.html
> --src
> ----index.js
> ----style.css
browser:
If you check in the terminal wewill find the url where our file is served locally. we will see something like this:
about css file:
normally we would add this:
<link rel="stylesheet" href="../style.css" />
inside our html file <head>
section.
But using webpack , we would import the css file in our main js file i.e ‘index.js’.
import “./style.css”;
Webpack turns the css codes into a string and pass it to the style-loader
which will output it as a <style>
in the <head>
of our index.html
.
about html file:
Don’t forget to add<script> pointing to the “main.js” inside “index.html”
<script src="main.js"></script>
End
So that is it. Now we can write beautiful modular javascript code using the latest es6 features and modules.