TypeScript is a superset of JavaScript that provides optional static typing, classes, and interfaces. It is used to build large-scale applications by adding more structure and safety to your code. Progressive Web Apps (PWAs) are web applications that use modern web capabilities to provide an app-like experience to users.
In this tutorial, we will explore how to use TypeScript to build a Progressive Web App.
Step 1: Create a new TypeScript project
The first step is to create a new TypeScript project. You can use any tool of your choice, but in this tutorial, we will use create-react-app to set up a new project. create-react-app is a popular tool used to create React projects quickly.
To create a new TypeScript project using create-react-app, open your terminal and run the following command:
npx create-react-app my-pwa --template typescriptThis command will create a new React project with TypeScript support. After the command finishes, navigate to the project directory by running:
cd my-pwa
Step 2: Install the PWA dependencies
Next, we need to install the dependencies required to turn our React app into a PWA. We will use workbox to create a service worker and react-app-rewired to customize the webpack configuration.
To install the dependencies, run the following command in your terminal:
npm install --save-dev workbox-webpack-plugin react-app-rewiredStep 3: Configure the PWA
To configure our app as a PWA, we need to create a manifest.json file and a service worker. We will use workbox to generate the service worker.
Create the manifest.json file
Create a new file named manifest.json in the public folder of your project. The manifest.json file describes your app and its properties. Here is an example manifest.json file:
{
"name": "My PWA",
"short_name": "My PWA",
"icons": [
{
"src": "logo192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "logo512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
Generate the service worker
To generate the service worker, we need to create a new file named sw.js in the public folder of your project. Here is an example sw.js file:
importScripts("https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js");
workbox.routing.registerRoute(
({request}) => request.destination === 'image',
new workbox.strategies.CacheFirst()
);
workbox.routing.registerRoute(
({request}) => request.destination === 'script',
new workbox.strategies.StaleWhileRevalidate()
);
workbox.routing.registerRoute(
({request}) => request.destination === 'style',
new workbox.strategies.StaleWhileRevalidate()
);
workbox.routing.registerRoute(
({request}) => request.destination === 'document',
new workbox.strategies.NetworkFirst()
);This code registers four routes: one for images that uses a CacheFirst strategy, one for scripts and styles that uses a StaleWhileRevalidate strategy, and one for documents that uses a NetworkFirst strategy.
Webpack configuration
To customize the Webpack configuration, we will use react-app-rewired. Create a new file named config-overrides.js in the root directory of your project with the following content:
const {WorkboxWebpackPlugin} = require('workbox-webpack-plugin');
const path = require('path');
module.exports = function override(config, env) {
config.plugins.push(
new WorkboxWebpackPlugin.GenerateSW({
clientsClaim: true,
skipWaiting: true,
})
);
// add custom aliases
config.resolve.alias = {
...config.resolve.alias,
'@': path.resolve(__dirname, 'src/'),
};
return config;
};This code adds a WorkboxWebpackPlugin plugin to the Webpack configuration and configures it to generate a service worker for us.
It also adds a custom alias for the src folder so that we can import our components and files easily.
Step 4: Modify App.tsx
Now that our PWA is configured, we need to modify our App.tsx file to use the PWA features.
import React, {useEffect} from 'react';
function App() {
useEffect(() => {
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js').then(registration => {
console.log('SW registered: ', registration);
}).catch(registrationError => {
console.log('SW registration failed: ', registrationError);
});
});
}
}, []);
return (
<div className="App">
{/* Your app components go here */}
</div>
);
}
export default App;This code adds an event listener for the load event and registers the service worker. The service worker will be loaded only if the serviceWorker API is available in the browser.
Step 5: Build and deploy the PWA
Finally, we need to build and deploy our PWA. To build the PWA, run the following command in your terminal:
npm run buildThis command will create a build folder with the compiled files.
To deploy the PWA, you can upload the contents of the build folder to your hosting provider. Your PWA is now live and ready to be installed on devices.
Conclusion
In this tutorial, we learned how to use TypeScript to build a Progressive Web App. We started by creating a new TypeScript project using create-react-app and installing the dependencies required to turn our app into a PWA. We then configured the PWA by creating a manifest.json file, generating a service worker, and customizing the Webpack configuration. Finally, we modified our App.tsx file to use the PWA features and built and deployed our PWA.