I’m trying to create web application using TS and Webpack, its name is “Shooter” – a basic game on browser. Today I’ll show you how to init the project with Typescript and use Webpack to bundle the code.
Prerequisites
Installed nodejs
Create a new folder, then open it by vscode
cd shooter
code .
Init npm and git
git init
In .gitignore file, add node_modules and dist to ignore them.
Init typescript config and webpack
Init typescript config file
Add ts-loader and webpack-cli to use webpack with typescript
npm install webpack-cli –save-dev
Create webpack.config.js file and add those configurations:
module.exports = {
entry: “./src/index.ts“,
module: {
rules: [
{
test: /.tsx?$/,
use: “ts-loader“,
exclude: /node_modules/,
},
],
},
resolve: {
extensions: [“.tsx“, “.ts“, “.js“],
},
output: {
filename: “bundle.js“,
path: path.resolve(__dirname, “dist“),
},
};
Create .ts file and test
Create src directory and index.ts file with some typescript code to test.
In package.json file, add this script inside scripts to build the code.
Build code by using
And you can see file bundle.js inside dist folder.
Add watch feature
To make webpack bundles code automatically each time you change code in src directory, add this script into package.json
Try to update code inside src directory and watch webpack bundles you code immediately.
Binding bundle.js with index.html
Create index.html file with some code in public directory.
Add html-webpack-plugin
Update add the plugin to webpack.config.js file
const HtmlWebpackPlugin = require(“html-webpack-plugin“);
module.exports = {
entry: “./src/index.ts“,
module: {
rules: [
{
test: /.tsx?$/,
use: “ts-loader“,
exclude: /node_modules/,
},
],
},
resolve: {
extensions: [“.tsx“, “.ts“, “.js“],
},
output: {
filename: “bundle.js“,
path: path.resolve(__dirname, “dist“),
},
plugins: [
new HtmlWebpackPlugin({
template: “public/index.html“,
}),
],
};
Now, run the project again, you will see the bundle.js is binding in header tag.
Use dev-server
To start you web application and apply watching code change in webpack, we can use web-pack-dev-server
Add this configuration in webpack.config.js
static: {
directory: path.join(__dirname, “dist“),
},
compress: true,
port: 9000,
},
Then finally add this script package.json
Now run the project with
And open http://localhost:9000/, you will see your application run there.