How to setup a new TypeScript project from scratch
Previously, we have written a guide for setting up a React application with TypeScript, you can read it here. In todays guide, we will cover the very basics and setup a simple TypeScript project and build the code to production ready JavaScript code. The idea with this guide is to be a baseline if you want to share the code to npmjs for example.
Create a new project
Start with creating a new project and install our dependencies.
mkdir ts-from-scratch cd ts-from-scratch npm init -y npm install typescript --save-dev (or npm install -g typescript) npm install --save-dev @babel/cli @babel/core @babel/preset-env @babel/preset-typescript
Babel
Create a .babelrc file in the root of the project.
{ "presets": ["@babel/preset-env", "@babel/preset-typescript"] }
tsconfig
Create tsconfig.json in the root of the project. More info about tsconfig can be found here.
{ "compilerOptions": { "target": "esnext", "moduleResolution": "node", "allowJs": true, "strict": true, "esModuleInterop": true, "declaration": true, "emitDeclarationOnly": true, "isolatedModules": true }, "include": ["src"] }
Our TypeScript class
Create a folder called src and a file called MyClass.ts in src folder. And let's add some example code with TypeScript syntax.
interface IMyClass { myFunction: () => void; } export default class MyClass implements IMyClass { myFunction() { console.log("myFunction"); } }
Build it
Now, when we have our amazing class that we want to share to the world, we need to make it compatible with JavaScript. So, let's setup our build script in package.json.
"scripts": { "build": "babel src --out-dir lib --extensions \".ts\"" },
Now, all our .ts files will be transpiled to JavaScript code and be listed in our lib folder that will be created when we run the script.
Run the build script
npm run build
And now we will have a new folder called lib with a MyClass.js file in it with the transpiled code that we can share with other applications.
Test the code
Just to make sure our code works. Let's create an index.js file in the root. And add following code.
const MyClass = require("./lib/MyClass").default; const myClass = new MyClass(); myClass.myFunction();
Now we will require the builded version of our MyClass and call our function. And run it like this.
node index.js
And it should print:
myFunction
in the console.
Outro
There we go. A very simple example of how we can build our TypeScript code into JavaScript. So, if you have a TypeScript project that you would like to share to other people, this guide could be a baseline for you to get started. Hope you enjoyed this guide!