Sådan tilføjes TypeScript til et JavaScript-projekt

Jeg elsker at skrive kode. Og jeg vil være rigtig god til det. Men på en eller anden måde har skrivning af JavaScript aldrig været min stærke kulør.

Uanset hvor meget jeg praktiserede, viste de samme fejl stadig i produktionen: cannot read property of undefinedundtagelser, den berømte [Object object]streng og endda funktionsopkald med et ugyldigt antal parametre.

Hvad mere er, de fleste af de kodebaser, jeg arbejdede på, var virkelig store JavaScript-dem. Så her er et godt diagram over, hvordan det føltes at være mig:

I dette indlæg undgår jeg at forklare, hvorfor TypeScript er fantastisk (og det er), og fokuserer på de opgaver, du skal udføre, hvis du vil migrere dit vanilje-JavaScript-projekt til et blandet TypeScript-projekt.

Ved afslutningen af ​​indlægget vil du være en lykkeligere person og være i stand til at besvare følgende spørgsmål:

  • Hvordan kan jeg tilføje typer til mit JavaScript-projekt?
  • Hvad er TypeScript?
  • Hvordan kan jeg bruge TypeScript i et JavaScript-projekt?
  • Hvad er trinene til at konvertere et JavaScript-program til at understøtte TypeScript?
  • Hvordan kan jeg tage mig af build & emballage?
  • Hvordan kan jeg passe på fnug?
  • Hvordan kan jeg "sælge" TypeScript til min organisation og udviklere?

Hvordan kan jeg tilføje typer til mit JavaScript-projekt?

Vanilla JavaScript understøtter ikke typer i øjeblikket, så vi har brug for en slags abstraktion oven på JavaScript for at gøre det.

Nogle almindelige abstraktioner bruger Facebooks statiske type-brik kaldet flowog Microsofts sprog hedder: typescript.

Dette blogindlæg vil undersøge brugen og tilføjelsen af ​​TypeScript til dit JavaScript-projekt.

Hvad er Typescript?

TypeScript er et indtastet supersæt af JavaScript, der kompileres til almindeligt JavaScript.

TypeScript består af et par dele. Den første er TypeScript-sproget - dette er et nyt sprog, der indeholder alle JavaScript-funktioner. Se specifikationerne for mere information.

Den anden er TypeScript-kompilatoren tsc( typesystemmotoren ), som er en kompilationsmotor, der bygger ts-filer og giver js-filer.

Hej verden i TypeScript

Som et eksempel er dette de trin, du skal tage for at skrive din første TypeScript-applikation:

  1. installer TypeScript med npm i typescript
  2. Opret en mappe kaldet exampleog cd ind i den (i din terminal)
  3. Opret en fil kaldet hello.world.ts
  4. skriv følgende kode i den:
const firstWords:string = "hello world" console.info(firstWords); 

og gem det derefter.

5. kør tsckommandoen for at køre TypeScript-kompilatoren på den aktuelle mappe

6. bemærk, at du har en hello.jsfil, som du nu kan køre :)

7. løb node ./hello.js

Hvordan kan jeg bruge TypeScript i et JavaScript-projekt?

Der er et par strategier til at udføre denne "migration" (virksomhedsmæssigt og kodemæssigt). Jeg har angivet dem nedenfor efter deres "omkostninger" og efter hvor meget værdi de giver.

Jeg vil foreslå at starte med "applikation TS support" og gå videre, når du har bevist værdien for dit udviklingsteam.

Metoden "lille skridt for mand" - Tilføjelse af TS-support til eksisterende applikationer

Mit første forslag er at oprette en blanding af de to sprog i et enkelt projekt og derefter skrive al "fremtidig" kode i TypeScript.

Kombinationen af ​​to sprog i et enkelt projekt lyder ret forfærdeligt i starten, men det fungerer ganske godt, da TS blev bygget til gradvis brug. Først kan den bruges lige som JS med .ts-filer og underlige importlinjer.

In this strategy, we will be compiling the migrated TypeScript files and just copying the JavaScript files to an output folder.

The huge benefit of this approach is that it allows a gradual learning curve for the development team (and for you) with language and it’s features. It also gives you hands-on experience and insight into its pros and cons.

I highly recommend starting from this step and then iterating on it with your team before moving forward. For a quick “how to do this”, scroll down to The steps to convert a javascript application to support typescript part.

The open for business approach - Adding TS support for existing libraries.

After you have some hands on experience with TS and your development team agrees it's worth moving forward, I suggest converting your in-house libraries and modules to support TS.

This can be done in two ways:

The first way involves using declaration files. A simple addition of d.ts files helps the TS compiler type-check existing JavaScript code and gives you auto-completion support in your IDE.

This is the "cheapest" option, as it doesn't require any code changes to the library at all. It also gives you maximum power and types support in your future code.

The second way is to perform a full re-write of TypeScript, which might be time-consuming and error-prone. I would advise against it, unless it proves ROI worthy to your team.

The skeleton - a step towards the future

I assume most developers are "lazy" and usually start their application by copying from a skeleton (which usually contains logging, metrics, configuration, and so on).

This step helps you navigate your way into a bright future, by creating an "official" skeleton for your company. It will be 100% TS, and deprecates the old JS skeleton if one exists.

This typescript-node-starter is a really good first project to start with.

The all in approach - Converting a full codebase from JS into TS

This option requires a total rewrite from JavaScript code to TypeScript.

I would recommend doing this as a final step in the TS migration process since it requires a total application re-write and deep knowledge of TypeScript and it's features.

You can do such a rewrite (it's a long process) in the following manner:

  1. Define clear types for your application business logic, API, & HTTP's
  2. Use @types packages for all the libraries in your package.json. Most of the libraries out there support TS, and in this process I suggest migrating them one by one (by just adding @types/ in your package.json file).
  3. Convert your application logical components in order of their importance. The more unique the business logic, the better.
  4. Convert the IO parts of your application, database layers, queues and so on.
  5. Convert your tests.

Keep in mind that there are automated tools designed to ease this process, for example ts-migrate from the Airbnb team.

It tackles this problem from a different perspective, and converts all files to TypeScript. It also allows gradual improvements (like mentioned in the steps above) while the entire codebase is TypeScript from day one.

How to convert a JavaScript application to support TypeScript.

Install typescript

by running : npm install typescript.

Typescript config file

Add a typescript config file, which can be created using the tsc --init command in you CLI.

Here is an example of how our initial config looked:

{ "compilerOptions": { "target": "esnext", "module": "commonjs", "allowJs": true, "checkJs": false, "outDir": "dist", "rootDir": ".", "strict": false, "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */ "declaration": true, /* Generates corresponding '.d.ts' file. */ "strictNullChecks": true, "resolveJsonModule": true, "sourceMap": true, "baseUrl": ".", "paths": { "*": [ "*", "src/*", "src/setup/*", "src/logic/*", "src/models/*", "config/*" ] }, }, "exclude": ["node_modules", "dist"], "include": [ "./src", "./test", "./*", "./config" ] }

A few things to notice above:

  • We read all the files in the src or test or config directory (using the include flag).
  • We accept JavaScript files as inputs (using the allowJs flag).
  • We emit all of the output files in build (using the outDirflag).

Create your first .TS file in your project

I recommend starting by adding a simple TypeScript file (or changing a really simple JS file to a TS one) and deploying. Take this migration one step at a time.

Take care of your package.json file

Here is how our package.json looks before and after:

{ "scripts": { "start": "node ./application.js", "mocha": "mocha --recursive --reporter spec -r test/bootstrap.js", "test": "npm run mocha -- test/ -r test/integration/bootstrap.js", } }
{ "scripts": { "start": "node ./dist/application.js", "build-dist": "./node_modules/typescript/bin/tsc", "mocha": "mocha --recursive --reporter spec -r ./dist/test/bootstrap.js", "test": "npm run mocha -- ./dist/test/ -r ./dist/test/integration/bootstrap.js" } }

As you can see, most of the changes were about adding the prefix dist to most of our build commands. We also added a build-dist script that compiles our codebase and moves all files to a dedicated folder called dist.

Add source-map-support

One of the big issues when adding TypeScript to your project is that you are adding a layer of indirection between the code you write and the code that actually runs in production (since .ts is transpiled  to .js  in run time).

For example, imagine the following TypeScript program:

const errorMessage: string = "this is bad" throw new Error(a)

When we run it, it will throw the following stack-trace:

Error: this is bad at Object. (/Users/dorsev/work/git/example/hello.js:3:7)

This is problematic since our code-base contains only .ts files. And since most production code contains hundreds of lines, it will be really time-consuming translating these numbers and files properly.

Luckily for us, there is a solution for this called source-map-support!

This allows us to ensure that stack-traces will have proper .ts file names and line numbers like we are used to :)

This can be done by running npm install source-map-support and then adding the following line in the first lines of your application:

require('source-map-support').install();

The code now looks like this:

require('source-map-support').install(); const a:string = "this is bad" throw new Error(a)

And when we compile it we run tsc --sourcemap hello.ts. Now we get the following stack-trace which is awesome :)

Error: this is bad at Object. (/Users/dorsev/work/git/example/hello.ts:3:7)

In recent versions of nodejs, this is supported natively by using the --enable-source-maps flag.

How to take care of your build (Travis) & packaging

Let's just examine the before and after changes on our build configuration file.

This is how our .travis file looked before (simplified edition):

jobs: include: - &build-and-publish before_script: - npm install --no-optional --production - npm prune --production before_deploy: - XZ_OPT=-0 tar --exclude=.git --exclude=reports.xml --exclude=${ARTIFACTS_MAIN_DIR} --exclude=.travis.yml --exclude=test -cJf "${ARTIFACTS_PATH}/${REPO_NAME}".tar.xz * .??* - &test before_script: - npm install --no-optional script: - echo "Running tests" - npm run lint && npm test

And this is how it looked after:

jobs: include: - &build-and-publish before_script: - npm install --no-optional --production - npm run build-dist # Build dist folder - npm prune --production before_deploy: - cp -rf config/env-templates ./dist/config/ - cp -rf node_modules ./dist/ - cd dist - XZ_OPT=-0 tar --exclude=.git --exclude=reports.xml --exclude=${ARTIFACTS_MAIN_DIR} --exclude=.travis.yml --exclude=test -cJf "${REPO_NAME}.tar.xz" * - mv ${REPO_NAME}.tar.xz "../${ARTIFACTS_PATH}" - cd .. - &test before_script: - npm install --no-optional - npm run build-dist script: - echo "Running tests" - npm run lint && npm test

Notice most changes concern "packaging" to the tar.xz file and running the build-dist command before accessing the dist folder.

How can I take care of linting?

There are a couple of linting solutions available.

The first solution we used was tsfmt  –  but then we decided against it later on because it requires you to maintain two separate configurations for your project (one for TypeScript using tsfmt and a separate one for JavaScript using eslint). The project also looks deprecated.

We then found TSLint  which redirected us to the eslint plugin for TypeScript. We then configured it as follows:

This was our eslintrc.js:

module.exports = { rules: { indent: [2, 2, { SwitchCase: 1 }], 'no-multi-spaces': 2, 'no-trailing-spaces': 2, 'space-before-blocks': 2, }, overrides: [{ files: ['**/*.ts'], parser: '@typescript-eslint/parser', plugins: ['@typescript-eslint'], extends: ['plugin:@typescript-eslint/eslint-recommended', 'plugin:@typescript-eslint/recommended'] }] }

Which we configured to run using a lint-fix command in our package.json which looks as follows:

{ "scripts": { "lint-fix": "node_modules/.bin/eslint . --fix" }, "pre-commit": ["lint-fix"] }

How to "sell" typescript to your development team

I believe one of the most critical aspects of introducing TypeScript to your organization is the "pitch" and how you present it to your development team.

Here is the presentation we presented internally which revolved around the following topics:

  1. Explain why we think TypeScript is awesome
  2. What is TypeScript
  3. Some basic code examples. The main point in this part is not to "teach" 100% TypeScript, since people will do that on their own. Instead, give people the feeling  that they can read and write TypeScript, and that the learning curve is not so hard.
  4. Advanced code examples, like Union types and Algebraic data-types which provide enormous values to a JS developer. This are a real treats, on top of typed-language and the compiler that will attract your developers to it.
  5. How to start using it. Encourage people to download the vs-code IDE and to add an annotation (//@ts-check) so they can start seeing the magic!  In our company, we prepared in advances some really cool mistakes that ts-check catches, and we did a live demo (2-3 minutes) to show how fast the TypeScript compiler can help them  using JS docs with type annotations or ts-check).
  6. Deep dive into some features. Explain ts.d files and @types packages which are some of the things you will encounter really early in your TypeScript codebases.
  7. Live PR's from your work. We showed the PR we created early on, and encouraged people to review it and try it out for themselves.
  8. Share some cool resources. There is a lot of content online, and it's hard to figure out good from bad. Do your teammates a solid and dig deeper and try to find quality content about the tools you use and need. Scroll down to the conclusion for my resources.
  9. Create a public pull request .  I recommend trying to get as much support as possible for its approval.

10.  Create a positive buzz in your organization about the change!

I highly recommend tweaking this list according to your team, standards, and time-constraints.

Conclusion

Typescript is super awesome! If you are writing production grade software and the business requirements and availability are high, I strongly encourage you to give typescript a try.

Just remember to take it one step at a time. New languages and frameworks are hard, so take the time to learn and to educate yourself and your team before pushing this process forward.

Create a short feedback loop and value proposition. It's hard to "sell" a new language to your team and management as it takes time and resources.

So design your migration process with short feedback loops, and try to define clear KPI's (fewer bugs in production, easier refactoring times, and so on) and make sure the value proposition for your use-case is constantly justified until it becomes the de-facto standard.  

Make learning resources readily available. I really enjoyed this talk about TypeScript first steps and this blog post about incremental migration to TypeScript.

Gå heller ikke glip af denoprojektet og ts-nodeprojektet. Jeg er meget begejstret og ser frem til at bruge dem snart.