How to add Typescript to an existing Webpack project
We have already read how to add React to an existing Webpack project and, similarly, we will now learn how to add Typescript to a Webpack project (React is supported!).
In this article we will see:
- required dependencies
- how to init Typescript
- Webpack configuration (with React support)
- allow Js files in Typescript project
Required dependencies to work with Webpack and Typescript
In 2021, this is straightforward. First, we need to install the necessary dependencies. Of course we need typescript, along with ts-loader which will allow Webpack to transpile the .ts and .tsx files.
To do so, we run the following command:
npm install --save-dev ts-loader typescript
Lastly, don’t forget to install react and react-dom types if you are in a ReactJS project:
npm install --save-dev @types/react @types/react-dom
Typescript initialization
In order to work with typescript, we need to create a tsconfig.json
file. In our case, we can create the file manually as the configuration we need is very simple.
Let’s create the tsconfig.json
file like so:
{
"compilerOptions": {
"sourceMap": true,
"jsx": "react",
"target": "ES6"
}
}
Webpack config with Typescript
To allow Webpack to load Typescript files, let’s add the ts-loader and add support for the .ts and .tsx extensions.
In the webpack.config.js
file, we add:
const path = require('path')
const webpack = require('webpack')
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/dist/',
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
{ test: /\.tsx?$/, loader: 'ts-loader' },
],
},
resolve: {
extensions: ['*', '.js', '.jsx', '.ts', '.tsx'],
},
plugins: [new webpack.HotModuleReplacementPlugin()],
devServer: {
contentBase: path.resolve(__dirname, './dist'),
hot: true,
},
}
At this point, we can test by creating an App.tsx
component:
import React from 'react'
interface AppProps {
title: string
href: string
}
const App: React.FC<AppProps> = ({ title, href }) => (
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
height: '100vh',
}}
>
<h1>
Hello World from <a href={href}>{title}</a>
</h1>
</div>
)
export default App
And in our index.js file:
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
ReactDOM.render(
<App title="Polynique" href="https://www.polynique.com" />,
document.getElementById('app')
)
// @ts-ignore
module.hot.accept()
Allow JS file in Typescript project
If we are adding typescript inside a project where we already have several .js files, right now we are not able to work with both extensions. This is because typescript does not support js extension by default.
To fix this issue, we just need to add in the tsconfig.json
file:
{
"compilerOptions": {
"sourceMap": true,
"jsx": "react",
"target": "ES6",
"allowJs": true,
"esModuleInterop": true,
}
}