Setup your own Webpack 4 config for React with Typescript

July 31, 2018・7 min read

Webpack has become one of the most important tools for modern web development and yet, it is a blackbox to many developers. In this tutorial, we are going to setup our own basic Webpack 4 configuration from scratch for React with Typescript.

If you just want to try something or build a simple side project, you should use the create-react-app with Typescript. There is no configuration needed, you can focus on coding.

Webpack’s core concepts

At its core, Webpack is a static module bundler for modern JavaScript applications. When Webpack processes your application, it internally builds a dependency graph which maps every module your project needs and generates one or more bundles.

To get started with Webpack, we only need to understand the following core concepts:

Entry

Output

Loaders

Plugins

The entry is which file, or module, should Webpack use to start resolving the dependencies. The default value in Webpack 4 is ./src/index.js .

The output property tells Webpack how to name the bundle files and where it should output them. The default value in Webpack 4 is the ./dist folder.

The loaders allow Webpack to process different types of imported files other than Javascript. Without loaders, Webpack only knows how to process Javascript files. Loaders allow you to create rules in your configuration file telling webpack to use a specific loader when it encounters a specific type of file.

Now if we run npm start, Webpack should be able to tranform and bundle our React code!

Adding HTML

I voluntarily didn’t create an HTML file yet, because we are going to use a Webpack plugin called html-webpack-plugin for that. This plugin will generate an HTML file using a template that we are going to give him, and automatically include our Webpack bundles inside the body:

Conclusion

We can now run npm start to start a development server with hot reloading and npm build to have a minimized bundle for production.

This is only a basic configuration of Webpack for a React project in Typescript. This article is already long so I didn’t add other features, but you should definitely push it further by adding other loaders, plugins and optimizing the configuration.