Webpack is a popular tool that we can use to bundle all our JavaScript code into the bundle.js file that our index.html is expecting.
- Install webpack and its command-line interface into our project as development dependencies, by entering the following command in the terminal:
npm install webpack webpack-cli --save-dev
- Webpack also has a handy web server that we can use during development. So, let's install that as well via the terminal:
npm install webpack webpack-dev-server --save-dev
- There's one final task to complete before we can start configuring webpack. This is to install a webpack plugin called ts-loader, which will help it load our TypeScript code. Install this as follows:
npm install ts-loader --save-dev
- Now that we have all this webpack stuff in our project, it's time to configure it. Create a file called webpack.config.js in the project root, and enter the following into it:
const path = require("path");
module.exports = {
entry: "./src/index.tsx",
module: {
rules: [
{
test: /.tsx?$/,
use: "ts-loader",
exclude: /node_modules/
}
]
},
resolve: {
extensions: [".tsx", ".ts", ".js"]
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.js"
},
devServer: {
contentBase: path.join(__dirname, "dist"),
compress: true,
port: 9000
}
};
There's a fair bit going on here, so let's break it down:
- The module.exports is our webpack configuration object.
- The entry field tells webpack where to start looking for modules to bundle. In our project, this is index.tsx.
- The module field tells webpack how different modules will be treated. Our project is telling webpack to use ts-loader to handle files with ts and tsx extensions.
- The resolve field tells webpack how to resolve modules. In our project, we need to process tsx and .ts files, as well as the standard .js files.
- The output field tells webpack where to bundle our code. In our project, this is the file called bundle.js in the dist folder.
- The devServer field configures the webpack development server. We are telling it that the root of the web server is the dist folder, and to serve files on port 9000.