Babel presets react typescript

@babel/preset-typescript

This preset is recommended if you use TypeScript, a typed superset of JavaScript. It includes the following plugins:

You will need to specify —extensions «.ts» for @babel/cli & @babel/node cli’s to handle .ts files.

Example​

Installation​

npm install --save-dev @babel/preset-typescript 
yarn add --dev @babel/preset-typescript 
pnpm add --save-dev @babel/preset-typescript 

Usage​

  "presets": ["@babel/preset-typescript"] > 

Via CLI​

babel --presets @babel/preset-typescript script.ts 

Via Node API​

require("@babel/core").transformSync("code",   presets: ["@babel/preset-typescript"], filename: 'script.ts', >); 

Options​

isTSX ​

boolean , defaults to false

Forcibly enables jsx parsing. Otherwise angle brackets will be treated as typescript’s legacy type assertion var foo = bar; . Also, isTSX: true requires allExtensions: true .

jsxPragma ​

string , defaults to React

Replace the function used when compiling JSX expressions. This is so that we know that the import is not a type import, and should not be removed.

jsxPragmaFrag ​

string , defaults to React.Fragment

Replace the function used when compiling JSX fragment expressions. This is so that we know that the import is not a type import, and should not be removed.

allExtensions ​

boolean , defaults to false

Indicates that every file should be parsed as TS, TSX, or as TS without JSX ambiguities (depending on the isTSX and disallowAmbiguousJSXLike options).

allowNamespaces ​

Enables compilation of TypeScript namespaces.

allowDeclareFields ​

boolean , defaults to false

NOTE: This will be enabled by default in Babel 8

When enabled, type-only class fields are only removed if they are prefixed with the declare modifier:

class A   declare foo: string; // Removed  bar: string; // Initialized to undefined  prop?: string; // Initialized to undefined  prop1!: string // Initialized to undefined > 

disallowAmbiguousJSXLike ​

boolean , defaults to true for .mts and .cts files and to false otherwise.

Even when JSX parsing is not enabled, this option disallows using syntax that would be ambiguous with JSX ( y type assertions and () => <> type arguments). It matches the tsc behavior when parsing .mts and .mjs files.

onlyRemoveTypeImports ​

boolean , defaults to false

When set to true , the transform will only remove type-only imports (introduced in TypeScript 3.8). This should only be used if you are using TypeScript >= 3.8.

optimizeConstEnums ​

boolean , defaults to false

When set to true , Babel will inline enum values rather than using the usual enum output:

// Input const enum Animals   Fish > console.log(Animals.Fish);  // Default output var Animals;  (function (Animals)   Animals[Animals["Fish"] = 0] = "Fish"; >)(Animals || (Animals = >));  console.log(Animals.Fish);  // `optimizeConstEnums` output console.log(0); 

This option differs from TypeScript’s —isolatedModules behavior, which ignores the const modifier and compiles them as normal enums, and aligns Babel’s behavior with TypeScript’s default behavior.

However, when exporting a const enum Babel will compile it to a plain object literal so that it doesn’t need to rely on cross-file analysis when compiling it:

// Input export const enum Animals   Fish, >  // `optimizeConstEnums` output export var Animals =   Fish: 0, >; 

You can read more about configuring preset options here.

Источник

How To Add TypeScript To Existing React Project

How To Add TypeScript To Existing React Project

Elevate your React project with TypeScript. By following easy steps like installing TypeScript, renaming .js files to .tsx creating a tsconfig.json file and updating your webpack or babel configuration, you can add TypeScript static type-checking and better code completion to your existing project.

Important disclosure: we’re proud affiliates of some tools mentioned in this guide. If you click an affiliate link and subsequently make a purchase, we will earn a small commission at no additional cost to you (you pay nothing extra). For more information, read our affiliate disclosure.

Install TypeScript As A Dev Dependency Using Npm Or Yarn

When you add TypeScript to an existing React project, you’ll need to install it as a dev dependency. This means that TypeScript won’t be included in your production build and will only be used during development.

To install TypeScript using npm, open a terminal window and navigate to your project directory. Then, run the following command:

npm install --save-dev typescript

This command will install the latest version of TypeScript and add it to your project’s package.json file as a dev dependency.

If you’re using yarn instead of npm, you can install TypeScript by running the following command:

This will add TypeScript to your project’s yarn.lock file as a dev dependency.

Once you’ve installed TypeScript, you’ll be able to use it in your project. For example, you could create a new file called MyComponent.tsx and start writing TypeScript code like this:

import React from 'react'; interface Props < name: string; >const MyComponent: React.FC = (< name >) => < return ( 

Hello, !

); >; export default MyComponent;

In this example, we’re importing React and defining an interface for the component’s props. We’re then using the React.FC type to define the component’s type, which includes the props interface. Finally, we’re exporting the component using the export default syntax.

Rename Your .js Files To .tsx

In React, components are typically defined in .js files. However, when using TypeScript, you’ll need to rename these files to .tsx so that TypeScript can recognize them as containing JSX syntax.

To rename your .js files to .tsx, simply locate the file you want to rename in your project’s directory and rename it by changing the file extension from .js to .tsx. For example, if you have a file called MyComponent.js , you should rename it to MyComponent.tsx .

Once you’ve renamed your .js files to .tsx, you’ll be able to start writing TypeScript code that uses JSX syntax.

Renaming your .js files to .tsx is a simple step, but it’s necessary if you want to use TypeScript in your existing React project.

Create A Tsconfig.json File At The Root Of Your Project

A tsconfig.json file is a configuration file that tells the TypeScript compiler how to compile your code. When you create a tsconfig.json file in the root of your project, TypeScript will automatically use it to configure the compilation process.

To create a tsconfig.json file, simply open a text editor and create a new file called tsconfig.json in the root of your project directory. Then, add the following configuration options:

In this configuration file, we’re specifying several options for the TypeScript compiler. For example, we’re setting the target to es5 , the module system to commonjs , and the JSX syntax to react . We’re also setting the output directory to ./dist , enabling strict type-checking, and allowing the use of import and export statements in CommonJS modules.

We’re also specifying the include option, which tells TypeScript which files to include in the compilation process. In this case, we’re including all files in the src directory and its subdirectories.

Once you’ve created your tsconfig.json file, TypeScript will use it to configure the compilation process. This means that you’ll be able to take advantage of TypeScript’s features, such as static type-checking and better code completion, in your existing React project.

Install The TypeScript Types For React And React DOM

When you add TypeScript to your project, you’ll need to install the TypeScript types for React and React DOM in order to use their type definitions. This will enable TypeScript to understand the structure and types of the React and React DOM libraries.

To install the TypeScript types for React and React DOM, you can use npm or yarn. Here’s how to do it using npm:

npm install --save-dev @types/react @types/react-dom

And here’s how to do it using yarn:

yarn add --dev @types/react @types/react-dom

Once you’ve installed these packages, you’ll be able to use the type definitions for React and React DOM in your TypeScript code.

Update Your Webpack.config.js Or Babel.config.js To Use The TypeScript Loader

When you add TypeScript to your project, you’ll need to update your webpack or babel configuration to use the TypeScript loader. This will ensure that your TypeScript code is compiled correctly and that your React components are correctly transpiled.

To update your webpack configuration, you’ll need to add a rule to your module configuration that tells webpack to use the ts-loader for .ts and .tsx files. Here’s an example:

module.exports = < // . module: < rules: [ < test: /\.(ts|tsx)$/, exclude: /node_modules/, use: 'ts-loader', >, // other rules. ], >, resolve: < extensions: ['.tsx', '.ts', '.js'], >, >;

In this example, we’re adding a new rule to the module configuration that matches .ts and .tsx files and excludes files in the node_modules directory. We’re also using the ts-loader to compile our TypeScript code.

We’re also adding the .tsx , .ts , and .js extensions to the resolve configuration, which tells webpack which file extensions to look for when resolving imports.

If you’re using babel instead of webpack, you’ll need to add the @babel/preset-typescript preset to your babel configuration. Here’s an example:

In this example, we’re adding the @babel/preset-typescript preset to our list of presets. This will ensure that babel can correctly transpile TypeScript code.

By updating your webpack or babel configuration to use the TypeScript loader or preset, you’ll be able to correctly compile your TypeScript code and use it in your React project.

Run Your Project With The TypeScript Compiler

Once you’ve installed TypeScript, renamed your .js files to .tsx , created a tsconfig.json file, installed the TypeScript types for React and React DOM, and updated your webpack or babel configuration to use the TypeScript loader or preset, you’re ready to run your project with the TypeScript compiler.

To do this, you can add a new script to your package.json file that runs the tsc command. Here’s an example:

In this example, we’ve added a new script called typecheck that runs the tsc command. This will compile your TypeScript code and check it for errors. You can run this script by running the following command in your terminal:

Or, if you’re using yarn, you can run:

Running the TypeScript compiler will help you catch errors early and ensure that your code is free of type-related issues. Once you’ve resolved any errors or warnings, you can use your existing start or build scripts to run or build your project as usual.

In conclusion, adding TypeScript to an existing React project can bring a host of benefits, including static type-checking, better code completion, and a more robust development experience overall. By following a few simple steps, including installing TypeScript as a dev dependency, renaming your .js files to .tsx , creating a tsconfig.json file, installing the TypeScript types for React and React DOM, and updating your webpack or babel configuration, you can start using TypeScript in your existing React project.

Once you’ve added TypeScript to your project, you can run it with the TypeScript compiler to catch errors early and ensure that your code is free of type-related issues. By doing so, you’ll be able to write more robust and maintainable code that will save you time and headaches in the long run.

Источник

Читайте также:  Возможности языка программирования си шарп
Оцените статью