Setting up Custom Webpack for TypeScript React
- By : Mydatahack
- Category : Front-End, Web Technologies
- Tags: React, TypeScript, Webpack
The easiest way to get started with React on TypeScript is to use create-react-app for TypeScript. As create-react-app uses webpack, you can eject config files by running npm run eject for further customisation.
What about building the project and webpack config from scratch? It is sometimes good to give it a go because you understand a little bit more about TypeScript React configuration. In this post, we will go through the steps to set up custom webpack for a TypeScript React project.
(1) Setting up folder
Here is the folder structure we use.
- root - src -components - public - dist - test
(2) Install dependencies
For all the React related modules, you need to add corresponding @type modules.
# install TypeScript npm i --save-dev typescript # install webpack npm i --save-dev webpack npm i --save-dev webpack-dev-server npm i --save-dev webpack-cli # install react and associated tools npm i --save react react-dom @types/react @types/react-dom npm i --save-dev ts-loader source-map-loader uglifyjs-webpack-plugin npm i --save-dev source-map-loader # install redux npm install -S redux react-redux @types/react-redux # install react router npm i -S react-router-dom @types/react-router-dom
(3) Add Webpack config
The bare minimum webpack config to get you started!
(4) Add tsconfig
On the root directly you need to add a tsconfig.json file. With TypeScript, you do not need Babel. TypeScript compiler converts the code into the version of JavaScript that runs on the browser.
If you need to import Json data directly from .json file, you need to set resolveJsonModule=true. The most importantly, skipLibCheck = true will make compilation time much faster for hot loading. Without this parameter, compilation takes noticeably longer and you will probably feel frustrated.
{ "compilerOptions": { "outDir": "./dist/", "sourceMap": true, "noImplicitAny": true, "module": "commonjs", "target": "es5", "jsx": "react", "resolveJsonModule": true, "skipLibCheck" : true }, "include" : [ "./src/**/*" ], "exclude" : [ "./test/**/*" ] }
(5) Add scripts in package.json
We can now add script to develop and build React application in package.json file.
"start": "webpack-dev-server --open", "devbuild": "webpack --mode development", "build": "webpack --mode production",
(6) File name consideration
With JavaScript, React works on both .js and .jsx extensions. With TypeScript, React only works on .tsx extension. For React components, make sure to use .tsx. The rest of the utility functions, you can use .ts extension.
(7) Next Steps
Check out the complete React-Redux example in TypeScript here. To set up unit test with Mocha and Enzyme, check out the post here.