Create Webpack Configuration File
Here I will add a config file and css
Create webpack.config.js file in root dir.
touch webpack.config.js
webpack.config.js
const path = require('path')
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
}
- Edit index.html script src from
main.jstobundle.js
index.html
<script src="bundle.js"></script>
- If you run
npm run buildagain it will use this config file this time and will give us/dist/bundle.jsinstead of main.js, but other then that this is the same setup as the zero config. So lets make it do something cool!
Adding css
- Get the proper webpack loaders,
style-loaderandcss-loader.yarn add style-loader css-loader
- Create a new file in the
srcdir.touch src/style.css
style.css
.title {
font-size: 40px;
color: #444;
font-family: sans-serif;
}
- import
style.cssinto yourindex.js
index.js
/*+*/ import './style.css'
var title = document.createElement('div')
/*+*/ title.className = 'title'
title.innerText = "Hello Webpack!"
document.body.appendChild(title)
- Add the necicery loaders to the webpack configuration
webpack.config.js
const path = require('path')
module.exports = {
mode: 'development', /* Let webpack know we are in development */
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.css$/,
use: [
{loader: 'style-loader'},
{loader: 'css-loader'}
]
}
]
}
}
Webpack will now import the css file and bundle it with the javascript. Later I will extract the css from the javascript. When using a lot of css this is a good idea, css and javascript load at the same time in the DOM, but having css in javascript will slow down load times.