In this post I will get you setting up typing in place in your JSS application. You might ask what it is for and why you would use it? Because it is great! It gives you type checking, forcing you to use types/interfaces and best of all, you'll have intellisense!
What I want to accomplish is that I change from the default script...
...to a typed component
Using flow you can keep on working in the JS, you just need to do some extra's:
- Install Flow by using the command
npm install -g flow-bin
- From the root of your project initialize Flow using the command
flow init. Run this command at the top level of your project to create one, empty file called
.flowconfig. At its most basic level,
.flowconfigtells the Flow background process the root of where to begin checking Flow code for errors.
// @flowto the top of your component. You now have the full power of Flow and its type-checking available to you.
When we now try to access properties on our component suddenly also have the intellisense:
falseor completely disable the built-in TypeScript extension for your project.
That's a mouth full! Flow is created and used by Facebook and when you search you'll see that more and more companies move to TypeScript. As an independent developer you could of course use your own poison but when working in teams the choice is often already made. Where I work we also use TypeScript, which is fine because I have been using it for some years now.
Main goal with this approach is that we still need to have a js-file as output. The scaffolding of a component outputs this for us and building our solution will require this too. If not you will get some unexpected behavior that your component is not there:
To get TypeScript working in JSS we need to do the following things:
- Make sure you have TypeScript installed:
npm i -g typescript
- Add the following packages to your project:
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
"start:tsc": "tsc -p .",to your
- Change the start script in
"start": "npm-run-all --serial bootstrap:disconnected --parallel start:react start:proxy start:watch-components start:tsc",
As an example rename the index.js of the ComtentBlock component by giving it a
.tsx extension. Also replace the contents of that component with the types code from this post (second piece of code). Make sure that line one is changed to
import * as React from 'react'; When you now run the command
tsc ./src/components/ContentBlock/index.tsx it will give you the following errors:
By default, the TypeScript compiler will process all files from the root. This includes the
node_modules folder. Therefore we must add some extra configuration for the compiler. Create a file with the name
tsconfig.json and paste the JSON from below. The error messages will be removed by setting
true . For the rest, just play around with the settings and see what suits your needs.