Sending many http request per each small file takes loading time. It makes your app slow.
- Check network tab (http request)
1️⃣ Install
npm install --save-dev webpack webpack-cli webpack-dev-server typescript ts-loader
webpack
: transform typescript code to javascript code and bundling them. ts-loader
: It helps webpack and typescript working together. .js
) with webpack.2️⃣ webpack.config.js
(development mode, default)
Filename
is up to you. (bundle.js
)publicPath
makes dev-server working(specify the base path for all the assets within your application).const path = require('path');
module.exports = {
mode: 'development',
entry: './src/app.ts',
devServer: {
contentBase: './dist',
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: 'dist'
},
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.ts', '.js'],
},
};
3️⃣ webpack.config.prod.js
(production mode)
webpack.config.prod.js
).CleanPlugin
removes cached files on dist folder when rebuilding an app in order to keep newest bundled file.const path = require('path');
const CleanPlugin = require('clean-webpack-plugin');
module.exports = {
mode: 'production',
entry: './src/app.ts',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.ts', '.js'],
},
plugins: [new CleanPlugin.CleanWebpackPlugin()],
};
4️⃣ package.json
"build": "webpack --config
will use chosen file not webpack.config.js
when running production mode."start": "webpack serve",
"build": "webpack --config webpack.config.prod.js"
5️⃣ index.html
<script type="module" src="dist/bundle.js"></script>