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
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
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
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.
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
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'
}
]
},