[Webpack] Basics

Intro

Video: https://www.youtube.com/watch?v=GU-2T7k9NfI

npm install webpack --save-dev

Webpack helps compose the frontend files and dependency imports.

package.json

1
2
3
4
"scripts":{
"build": "webpack src/js/app.js dist/bundle.js", // webpack ENTRYPOINT TARGET
"build prod": "webpack src/js/app.js dist/bundle.js -p" // production mode, with minified code
}

Webpack dev server

npm install --save-dev webpack-dev-server

package.json

1
2
3
"scripts":{
"build": "webpack-dev-server --entry ./src/js/app.js --output-filename ./dist/bundle.js",
}

npm run build will serve the files from local server.

Webpack core concepts

entry => module loaders => plugins => output

webpack.config.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
const path = require('path');
const webpack = require('webpack');

module.exports = {
entry: './src/js/app.js', // define the entry point and get all its imports
output: {
path: path.resolve(__dirname, 'dist'), // the output path needs to be an absolute path, and the __dirname is the absolute path to the current directory
filename: 'bundle.js',
publicPath: '/dist' // where should the webpack server look for the output
},
module: {
rules: [
{
test: /\.css$/, // lets the webpack know how does specific rule apply
// loader: 'css-loader', // allows the javascript file to import css, but don't make it compiled
use: [ // use multiple loaders, order is IMPORTANT, the compile order is reversed, the bottom loads FIRST!!
'style-loader', // inject css in DOM
'css-loader',
]
},
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({ // minify the bundle code
//...
})
]
}

package.json

1
2
3
4
"scripts":{
"build": "webpack-dev-server",
"biuld:prod": "webpack -p"
}

Loader & Modules

Modules and loaders allow us to transform the files.

npm install css-loader style-loader --save-dev

  • Loaders are applied on a file base
  • Plugins are applied to the whole bundle

Babel + SCSS example: https://www.youtube.com/watch?v=8vnkM8JgjpU&list=PL55RiY5tL51rcCnrOrZixuOsZhAHHy6os&index=4