address app to add edit delete address entry
Refactoring code on my old side-project.
In hope to learn and be more comfortable with TypeScripts and DUCKs redux file structure and feature-first file structure to build scalable project, I have started to refactor this simple addressBookApp which is the conventional functionality-first approach React app.
npm install
npm run start:dev
npm start
(to test) npm test
In order to convert existing react app to Typesciprt, it requires 2 changes:
Install dependencies:
If you have CRA (react-scripts@2.1.0 or higher):
Facebook Guide source
react-scripts:"...."
. If its version is lower than 2.1.0 then manually add “2.1.0” or higher.$ npm install
to reinstall. $ npm install --save-dev typescript awesome-typescript-loader source-map-loader
- awesome-typescript-loader : webpack plugin to compile ts into js (like babel loader for babel)
- source-map-loader : adds source map support for debugging
$ npm install --save @types/react @types/react-dom
- installs type declaration files (.d.ts files) from @types for any library in use.
Configure TypeScript
Create a typescript config file to configure TypesScript (tsconfig.json in the root folder of the app)
<!-- tsconfig.json file -->
{
"compilerOptions": {
"outDir": "./dist/", // path to output directory
"sourceMap": true, // allow sourcemap support
"strictNullChecks": true, // enable strict null checks as a best practice
"module": "es6", // specify module code generation
"jsx": "react", // use typescript to transpile jsx to js
"target": "es5", // specify ECMAScript target version
"allowJs": true, // allow a partial TypeScript and JavaScript codebase
"moduleResolution": "node" // fixes csstype bug
},
"include": [
"./src/**/*" // where ts files that needs to be compiled to js reside
]
}
Setup Build pipeline
Modify webpack.config.js file in order to add TypeScript compilation as a part of build process.
Required changes are:
<!-- webpack.config.js file -->
module.exports = {
// change to .tsx if necessary
entry: './src/app.jsx',
output: {
filename: './dist/bundle.js'
},
resolve: {
// changed from extensions: [".js", ".jsx"]
extensions: [".ts", ".tsx", ".js", ".jsx"]
},
module: {
rules: [
// changed from { test: /\.jsx?$/, use: { loader: 'babel-loader' } },
{ test: /\.(t|j)sx?$/, use: { loader: 'awesome-typescript-loader' } },
// addition - add source-map support
{ enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
]
},
externals: {
"react": "React",
"react-dom": "ReactDOM",
},
// addition - add source-map support
devtool: "source-map"
}
$ npx webpack
(installation of npx is required $ npm install -g npx
).js —> .ts
or .jsx --> .tsx
extensions in filesimport * as React from react
React.Component
by the end of eract.Component<any, any>
. Convert the entire codebase
After each step always bundle the app by running $ npx webpack