Skip to content

Instantly share code, notes, and snippets.

@rstacruz
Last active January 17, 2024 22:27
Show Gist options
  • Save rstacruz/648cb4dc68a76c761dc9e989832d9a50 to your computer and use it in GitHub Desktop.
Save rstacruz/648cb4dc68a76c761dc9e989832d9a50 to your computer and use it in GitHub Desktop.
Setting up Babel and TypeScript

Install Babel 7 and TypeScript

yarn add --dev \
  @babel/core \
  @babel/cli \
  @babel/preset-env \
  @babel/preset-typescript \
  typescript

Babel config

Configure babel.config.js to add preset-typescript in there.

module.exports = {
  presets: ['@babel/preset-typescript', '@babel/preset-env']
}

TypeScript config

Create tsconfig.json.

{
  "compilerOptions": {
    // Target latest version of ECMAScript.
    "target": "esnext",
    // Search under node_modules for non-relative imports.
    "moduleResolution": "node",
    // Process & infer types from .js files.
    "allowJs": true,
    // Don't emit; allow Babel to transform files.
    "noEmit": true,
    // Enable strictest settings like strictNullChecks & noImplicitAny.
    "strict": true,
    // Import non-ES modules as default imports.
    "esModuleInterop": true,
    "jsx": "react"
  },
  "include": [
    "src" // <-- change this to where your source files are
  ]
}

Add tsc script

Add the tsc script to your package.json. Configure your CI to run yarn run tsc for checks.

"scripts": {
  "watch": "babel --watch src ---out-dir lib --extensions '.ts,.tsx'",
  "build": "babel src --out-dir lib --extensions '.ts,.tsx'",
  "tsc": "tsc"
}

Just run tsc

This will run type checks.

yarn run tsc

Also see

@roywillemse
Copy link

For anyone else who still has some js and jsx files in their project along with ts and tsx files you can use the following in your package.json:

"scripts": {
  "watch": "babel --watch src ---out-dir lib --extensions '.js,.ts,.tsx,.jsx'",
  "build": "babel src --out-dir lib --extensions '.js,.ts,.tsx,.jsx'",
  "tsc": "tsc"
}

@hddananjaya
Copy link

There is an extra - in --out-dir. Don't forget to remove it as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment