TypeScript-Babel-Starter
A sample setup using Babel CLI to build TypeScript code, and using TypeScript for type-checking.
Top Related Projects
🐠 Babel is a compiler for writing next generation JavaScript.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
Set up a modern web app by running one command.
The React Framework
Cybernetically enhanced web apps
This is the repo for Vue 2. For Vue 3, go to https://github.com/vuejs/core
Quick Overview
The TypeScript-Babel-Starter is a template repository provided by Microsoft to help developers quickly set up a project using TypeScript and Babel. It offers a pre-configured environment that combines the type-checking capabilities of TypeScript with the transpilation features of Babel, allowing for a modern development workflow.
Pros
- Seamless integration of TypeScript and Babel
- Pre-configured setup saves time and reduces initial setup complexity
- Includes Jest for testing out of the box
- Supports both CommonJS and ES modules
Cons
- May require additional configuration for more complex projects
- Some developers might prefer a simpler TypeScript-only setup
- Limited customization options in the initial template
- Potential learning curve for developers new to Babel or TypeScript
Code Examples
- Basic TypeScript code:
// src/index.ts
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet("TypeScript"));
- Using async/await (transpiled by Babel):
// src/async-example.ts
async function fetchData(): Promise<string> {
const response = await fetch('https://api.example.com/data');
return response.text();
}
fetchData().then(console.log);
- Jest test example:
// src/__tests__/index.test.ts
import { greet } from '../index';
test('greet function', () => {
expect(greet('Jest')).toBe('Hello, Jest!');
});
Getting Started
-
Clone the repository:
git clone https://github.com/microsoft/TypeScript-Babel-Starter.git cd TypeScript-Babel-Starter
-
Install dependencies:
npm install
-
Start development:
npm run build npm start
-
Run tests:
npm test
Competitor Comparisons
🐠 Babel is a compiler for writing next generation JavaScript.
Pros of Babel
- More comprehensive and feature-rich, supporting a wide range of JavaScript transformations
- Larger community and ecosystem, with numerous plugins and presets available
- Actively maintained with frequent updates and improvements
Cons of Babel
- Steeper learning curve due to its extensive configuration options
- Potentially slower build times for large projects compared to TypeScript-Babel-Starter
- May require additional setup for TypeScript integration
Code Comparison
TypeScript-Babel-Starter:
{
"presets": [
"@babel/preset-env",
"@babel/preset-typescript"
]
}
Babel:
{
"presets": [
["@babel/preset-env", { "targets": { "node": "current" } }],
"@babel/preset-typescript"
],
"plugins": [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-proposal-object-rest-spread"
]
}
The TypeScript-Babel-Starter configuration is simpler and focused on TypeScript integration, while the Babel configuration offers more flexibility and additional features through plugins.
TypeScript-Babel-Starter is designed specifically for TypeScript projects using Babel, providing a streamlined setup. Babel, on the other hand, is a more versatile tool that can be used for various JavaScript transformations, including TypeScript support when properly configured.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
Pros of TypeScript
- Comprehensive TypeScript implementation and tooling
- Extensive documentation and community support
- Regular updates and maintenance from Microsoft
Cons of TypeScript
- Larger repository size, potentially overwhelming for beginners
- Steeper learning curve due to its comprehensive nature
- Less flexibility in configuration compared to Babel-based setups
Code Comparison
TypeScript:
// Example from TypeScript compiler
function createMap<T>(): Map<string, T> {
return new Map<string, T>();
}
TypeScript-Babel-Starter:
// Example from TypeScript-Babel-Starter
const map: Map<string, number> = new Map();
map.set("key", 123);
Key Differences
- TypeScript focuses on the core language implementation and compiler
- TypeScript-Babel-Starter provides a minimal setup for TypeScript with Babel
- TypeScript-Babel-Starter offers more flexibility in transpilation options
- TypeScript provides a more comprehensive development environment
Use Cases
- Choose TypeScript for deep TypeScript development and contributions
- Opt for TypeScript-Babel-Starter for quick project setups with Babel integration
Community and Support
- TypeScript has a larger community and more extensive resources
- TypeScript-Babel-Starter is suitable for those familiar with Babel ecosystems
Set up a modern web app by running one command.
Pros of Create React App
- Provides a complete, production-ready React development environment
- Includes built-in support for CSS modules, SASS, and other popular tools
- Offers a smoother learning curve for beginners in React development
Cons of Create React App
- Less flexibility in configuration compared to TypeScript-Babel-Starter
- Larger bundle size due to included features that may not be necessary for all projects
- Potential difficulties when ejecting or customizing the build process
Code Comparison
TypeScript-Babel-Starter:
import * as React from 'react';
import * as ReactDOM from 'react-dom';
const App: React.FC = () => <h1>Hello, World!</h1>;
ReactDOM.render(<App />, document.getElementById('root'));
Create React App:
import React from 'react';
import ReactDOM from 'react-dom';
const App = () => <h1>Hello, World!</h1>;
ReactDOM.render(<App />, document.getElementById('root'));
The main difference is that TypeScript-Babel-Starter uses TypeScript syntax with explicit type imports, while Create React App uses standard JavaScript (or optionally TypeScript) with more concise import statements. Create React App also includes additional setup and configuration files not shown here.
The React Framework
Pros of Next.js
- Full-featured React framework with built-in routing, server-side rendering, and API routes
- Extensive ecosystem with plugins and integrations for various use cases
- Automatic code splitting and optimized performance out of the box
Cons of Next.js
- Steeper learning curve for developers new to server-side rendering concepts
- More opinionated structure, which may limit flexibility in some scenarios
- Larger bundle size compared to minimal TypeScript-Babel setups
Code Comparison
Next.js:
// pages/index.js
export default function Home() {
return <h1>Welcome to Next.js!</h1>
}
TypeScript-Babel-Starter:
// src/index.ts
const greeting: string = "Hello, TypeScript!";
console.log(greeting);
Summary
Next.js offers a comprehensive framework for building React applications with server-side rendering capabilities, while TypeScript-Babel-Starter provides a minimal setup for TypeScript projects using Babel. Next.js is better suited for large-scale applications requiring advanced features, whereas TypeScript-Babel-Starter is ideal for smaller projects or as a foundation for custom build configurations. The choice between the two depends on project requirements, team expertise, and desired level of control over the development environment.
Cybernetically enhanced web apps
Pros of Svelte
- Offers a complete framework for building web applications, not just a starter template
- Provides a more efficient runtime with smaller bundle sizes
- Features a simpler, more intuitive syntax for reactive programming
Cons of Svelte
- Less established ecosystem compared to TypeScript and Babel
- Steeper learning curve for developers familiar with traditional JavaScript frameworks
- Limited tooling support compared to TypeScript
Code Comparison
TypeScript-Babel-Starter:
import { sayHello } from "./greet";
console.log(sayHello("TypeScript"));
Svelte:
<script>
let name = 'Svelte';
</script>
<h1>Hello {name}!</h1>
The TypeScript-Babel-Starter example showcases TypeScript syntax and module imports, while the Svelte example demonstrates its component-based approach with built-in reactivity.
TypeScript-Babel-Starter is primarily a configuration template for using TypeScript with Babel, ideal for developers who want to integrate these tools into their existing projects. Svelte, on the other hand, is a full-fledged framework that compiles to vanilla JavaScript, offering a different approach to building web applications with its own syntax and conventions.
This is the repo for Vue 2. For Vue 3, go to https://github.com/vuejs/core
Pros of Vue
- More comprehensive framework with built-in state management and routing
- Larger ecosystem and community support
- Easier learning curve for beginners
Cons of Vue
- Less flexibility for custom build configurations
- Potentially heavier bundle size for small projects
- Opinionated structure may not suit all project types
Code Comparison
Vue component:
<template>
<div>{{ message }}</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello Vue!'
}
}
}
</script>
TypeScript-Babel-Starter component:
import React from 'react';
const HelloWorld: React.FC = () => {
return <div>Hello TypeScript!</div>;
};
export default HelloWorld;
Summary
Vue is a more complete framework offering a full-featured development experience, while TypeScript-Babel-Starter provides a minimal setup for TypeScript and Babel integration. Vue excels in rapid development and ease of use, particularly for newcomers. However, TypeScript-Babel-Starter offers more flexibility in terms of build configuration and is lighter weight for smaller projects. The choice between the two depends on project requirements, team expertise, and desired level of control over the development environment.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
TypeScript-Babel-Starter
What is this?
This is a small sample repository that uses Babel to transform TypeScript to plain JavaScript, and uses TypeScript for type-checking. This README will also explain step-by-step how you can set up this repository so you can understand how each component fits together.
For simplicity, we've used babel-cli
with a bare-bones TypeScript setup, but we'll also demonstrate integration with JSX/React, as well as adding bundlers into the mix.
Specifically, we'll show off integration with Webpack for if you're deploying an application, and Rollup for if you're producing a library.
How do I use it?
Building the repo
npm run build
Type-checking the repo
npm run type-check
And to run in --watch
mode:
npm run type-check:watch
How would I set this up myself?
Install your dependencies
Either run the following:
npm install --save-dev typescript @babel/core @babel/cli @babel/plugin-proposal-class-properties @babel/preset-env @babel/preset-typescript
or make sure that you add the appropriate "devDependencies"
entries to your package.json
and run npm install
:
"devDependencies": {
"@babel/cli": "^7.8.3",
"@babel/core": "^7.8.3",
"@babel/plugin-proposal-class-properties": "^7.8.3",
"@babel/preset-env": "^7.8.3",
"@babel/preset-typescript": "^7.8.3",
"typescript": "^3.7.5"
}
Create your tsconfig.json
Then run
tsc --init --declaration --allowSyntheticDefaultImports --target esnext --outDir lib
Note: TypeScript also provides a --declarationDir
option which specifies an output directory for generated declaration files (.d.ts
files).
For our uses where --emitDeclarationOnly
is turned on, --outDir
works equivalently.
Create your .babelrc
Then copy the .babelrc
in this repo, or the below:
{
"presets": [
"@babel/preset-env",
"@babel/preset-typescript"
],
"plugins": [
"@babel/plugin-proposal-class-properties"
]
}
Set up your build tasks
Add the following to the "scripts"
section of your package.json
"scripts": {
"type-check": "tsc --noEmit",
"type-check:watch": "npm run type-check -- --watch",
"build": "npm run build:types && npm run build:js",
"build:types": "tsc --emitDeclarationOnly",
"build:js": "babel src --out-dir lib --extensions \".ts,.tsx\" --source-maps inline"
}
How do I change it?
Using JSX (and React)
Full example available here
Install your dependencies
Install the @babel/preset-react package as well as React, ReactDOM, and their respective type declarations
npm install --save react react-dom @types/react @types/react-dom
npm install --save-dev @babel/preset-react
Update .babelrc
Then add "@babel/react"
as one of the presets in your .babelrc
.
Update tsconfig.json
Update your tsconfig.json
to set "jsx"
to "react"
.
Use a .tsx
file
Make sure that any files that contain JSX use the .tsx
extension.
To get going quickly, just rename src/index.ts
to src/index.tsx
, and add the following lines to the bottom:
import React from 'react';
export let z = <div>Hello world!</div>;
Using Webpack
Full example available here
Install your dependencies
npm install --save-dev webpack webpack-cli babel-loader
Create a webpack.config.js
Create a webpack.config.js
at the root of this project with the following contents:
var path = require('path');
module.exports = {
// Change to your "entry-point".
entry: './src/index',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'app.bundle.js'
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.json']
},
module: {
rules: [{
// Include ts, tsx, js, and jsx files.
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
loader: 'babel-loader',
}],
}
};
Create a build task
Add
"bundle": "webpack"
to the scripts
section in your package.json
.
Run the build task
npm run bundle
Using Rollup
Full example available here
Install your dependencies
npm install --save-dev rollup @rollup/plugin-babel @rollup/plugin-node-resolve @rollup/plugin-commonjs
Create a rollup.config.js
Create a rollup.config.js
at the root of this project with the following contents:
import commonjs from '@rollup/plugin-commonjs';
import resolve from '@rollup/plugin-node-resolve';
import babel from '@rollup/plugin-babel';
import pkg from './package.json';
const extensions = [
'.js', '.jsx', '.ts', '.tsx',
];
const name = 'RollupTypeScriptBabel';
export default {
input: './src/index.ts',
// Specify here external modules which you don't want to include in your bundle (for instance: 'lodash', 'moment' etc.)
// https://rollupjs.org/guide/en#external-e-external
external: [],
plugins: [
// Allows node_modules resolution
resolve({ extensions }),
// Allow bundling cjs modules. Rollup doesn't understand cjs
commonjs(),
// Compile TypeScript/JavaScript files
babel({ extensions, include: ['src/**/*'] }),
],
output: [{
file: pkg.main,
format: 'cjs',
}, {
file: pkg.module,
format: 'es',
}, {
file: pkg.browser,
format: 'iife',
name,
// https://rollupjs.org/guide/en#output-globals-g-globals
globals: {},
}],
};
Create a build task
Add
"bundle": "rollup -c"
to the scripts
section in your package.json
.
Run the build task
npm run bundle
Using NodeJS
Full example available here
Install your dependencies
npm install --save-dev @babel/core @babel/node @babel/plugin-proposal-class-properties @babel/preset-env @babel/preset-typescript typescript
Create a start task
Add
"start": "babel-node -x \".ts\" src/index.ts"
to the scripts
section in your package.json
.
Run the start task
npm run start
Top Related Projects
🐠 Babel is a compiler for writing next generation JavaScript.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
Set up a modern web app by running one command.
The React Framework
Cybernetically enhanced web apps
This is the repo for Vue 2. For Vue 3, go to https://github.com/vuejs/core
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot