I discovered two functional projects, https://github.com/StopNGo/react-proto and https://github.com/galenweber/simple-react-typescript-ssr, for SSR TypeScript templates. Both of these projects use webpack.
This video is a good introduction to understanding webpack’s capabilities.
Install the VSCode Live Server Extension to enable the “open with live server” option when right-clicking on index.html.
Use npm i -D webpack webpack-cli
to install dependencies and include "build": "webpack --mode production"
in the package.json/scripts to bundle JavaScript files.
Create webpack.config.js
Control generated bundle file
1 2 3 4 5 6 7 8 9 10 11 12 13 | const path = require( 'path' ) module.exports = { mode: 'development' , entry: { bundle: path.resolve(__dirname, 'src/index.js' ) }, output: { path: path.resolve(__dirname, 'dist' ), filename: '[name].js' } } |
SASS
Run npm i -D sass style-loader css-loader sass-loader
and config in the webpack.config.js
1 2 3 4 5 6 7 8 | module: { rules: [ { test:/\.scss$/, use: [ 'style-loader' , 'css-loader' , 'sass-loader' ] } ] } |
Automatically generated dist
We wish dist folder is automatically generated. To achieve this, run npm i -D html-webpack-plugin
and configure in the webpack.config.js.
Dev server
Run npm i -D webpack-dev-server
, add “dev”: “webpack serve” in package.json, and config in the webpack.config.js
1 2 3 4 5 6 7 8 9 10 | devServer: { static : { directory: path.resolve(__dirname, 'dist' ) }, port: 3000, open: true , hot: true , compress: true , historyApiFallback: true } |
Babel
Run npm i -D babel-loader @babel/core @babel/preset-env
and change webpack.config.js, so that JavaScript can be supported by various browsers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | module: { rules: [ { test:/\.scss$/, use: [ 'style-loader' , 'css-loader' , 'sass-loader' ] }, { test:/\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader' , options: { presets: [ '@babel/preset-env' ] } } } ] }, |
Images
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 | output: { path: path.resolve(__dirname, 'dist' ), filename: '[name].[contenthash].js' , clean: true , assetModuleFilename: '[name][ext]' }, module: { rules: [ { test:/\.scss$/, use: [ 'style-loader' , 'css-loader' , 'sass-loader' ] }, { test:/\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader' , options: { presets: [ '@babel/preset-env' ] } } }, { test: /\.(png|svg|jpg|jpeg|gif)$/i, type: 'asset/resource' } ] }, |