Webpack Demo 2

xiaoyu chen
2 min readJun 3, 2021

This article is to apply Webpack into game 2048 project. The source code is

Project structure

Prepare

Heading to package.json, to install devDependencies. For example …

npm i -D webpack webpack-cli webpack-dev-server

Webpack config

1. Entry

Set ./src/js/index.js as entry point.

2. Output

All the bundles are in build. [contenthash:10] is for lazy loading.

3. Loader and Plugin

Css, Less, Sass

less-loader: translate less into css

sass-loader: translate sass into css

css-loader: translate css into ‘string’ in js file via common.js

style-loader: create style label, add them into head

mini-css-extract-plugin: this plugin can help to extract css into a css file

postcss-loader, postcss-preset-env : handle css compatibility. And setup the browsers list in package.json

optimize-css-assets-webpack-plugin: compress css file

For example,

[MiniCssExtractPlugin.loader, ‘css-loader’, ‘postcss-loader’, ‘less/sass-loader’]

Html

html-webpack-plugin : create an empty HTML, import all resources (JS, CSS) automatically.

Images

url-loader: translate images, but it can’t translate the images in html

html-loader: translate the images in html

Other resources

file-loader: translate others resources (fonts), except html/css/js

JS Eslint and Babel

Prettier can format code style, and eslint can check JS code.

PS: eslint-loader is working in webpack4, eslint-webpack-plugin is working in webpack 5.

eslint-webpack-plugin: it can check all the js/json… file

eslint, eslint-config-airbnb-base, eslint-plugin-import: setup “eslintConfig” in package.json.

babel-loader @babel/core @babel/preset-env @babel/polyfill core-js: Handle JS compatibility.

@babel/preset-env only handle basic js, it can’t handle Promise

@babel/polyfill : implement above issues, handle all JS compatibility

core-js: if using polyfill, it will import all methods of handling compatibility. If only want to compatible some specify browsers, using core-js.

Webpack optimisation

HMR

HMR is Hot Module Replacement. Situation: If you have 2 JS file (ACSS, BCSS), if you change ACSS, and then it’ll compile all the files. However, if setup HMR, it will only re-compile ACSS.

devServer:{ hot: true}

CSS: support HMR, as style-loader already handle it

JS: do not support HMR => update JS code to fix this problem. (module.hot)

html: do not support HMR, and html can’t hot update. => put html into entry point

Source-map

It can developer to look for and debug the errors

devtool: “source-map”,

Babel Cache

cacheDirectory: true, js/built.[contenthash:10].js

When re-built project, if file content change, the name of file will be changed. In this case, webpack will only compile ‘changed file’.

Code split

Lazy loading & Pre loading

PWS

--

--