TSConfig
- TSConfig
Abaixo há um modelo para projetos novos
{
"compilerOptions": {
"target": "ES2022",
"moduleResolution": "nodenext",
"module": "NodeNext",
"rootDir": "./src",
"outDir": "./dist",
"removeComments": true,
"importsNotUsedAsValues": "remove",
"downlevelIteration": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipDefaultLibCheck": true,
"skipLibCheck": true,
}
}
//package.json -> "type": "module"
Bases of TSConfig
Propriedades
Opções
npx tsc —noEmit- Ele não gera o arquivo transpilado, mas faz a checagem dos tipos e mostra no console se tem algo errado
npx tsc —noEmit —explainFilesnpx tsc —outDir dist- Arquivos compilados são emitidos dentro de uma nova pasta chamada
dist
- Arquivos compilados são emitidos dentro de uma nova pasta chamada
Artigo Cheat Sheet
tsconfig.json scares everyone. It's a huge file with a TON of potential options.
But really, there are only a few configuration options you need to care about. Let's figure them out, and cheatsheet them.
Quickstart
Want just the code? Here you go:
{
"compilerOptions": {
/* Base Options: */
"esModuleInterop": true,
"skipLibCheck": true,
"target": "es2022",
"allowJs": true,
"resolveJsonModule": true,
"moduleDetection": "force",
"isolatedModules": true,
"verbatimModuleSyntax": true,
/* Strictness */
"strict": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
/* If transpiling with TypeScript: */
"module": "NodeNext",
"outDir": "dist",
"sourceMap": true,
/* AND if you're building for a library: */
"declaration": true,
/* AND if you're building for a library in a monorepo: */
"composite": true,
"declarationMap": true,
/* If NOT transpiling with TypeScript: */
"module": "preserve",
"noEmit": true,
/* If your code runs in the DOM: */
"lib": ["es2022", "dom", "dom.iterable"],
/* If your code doesn't run in the DOM: */
"lib": ["es2022"],
/*Esta opção, quando ativada, faz com que o TypeScript gere um erro sempre que uma variável local é declarada em um determinado escopo, mas nunca é lida ou utilizada de qualquer forma. Isso ajuda a identificar e remover variáveis redundantes que podem ter sido deixadas no código por engano ou após refatorações. */
"noUnusedLocals": true,
/*Similarmente, essa opção gera um erro quando um parâmetro de função é declarado mas nunca utilizado dentro dessa função. Isso é particularmente útil para limpar as interfaces das funções após mudanças no código, garantindo que todos os parâmetros listados são realmente necessários */
"noUnusedParameters": true
}
}
Full Explanation
Base Options
Here are the base options I recommend for all projects.
{
"compilerOptions": {
"esModuleInterop": true,
"skipLibCheck": true,
"target": "es2022",
"allowJs": true,
"resolveJsonModule": true,
"moduleDetection": "force",
"isolatedModules": true,
"verbatimModuleSyntax": true
}
}
esModuleInterop: Helps mend a few of the fences between CommonJS and ES Modules.skipLibCheck: Skips checking the types of.d.tsfiles. This is important for performance, because otherwise allnode_moduleswill be checked.target: The version of JavaScript you're targeting. I recommendes2022overesnextfor stability.allowJsandresolveJsonModule: Allows you to import.jsand.jsonfiles. Always useful.moduleDetection: This option forces TypeScript to consider all files as modules. This helps to avoid 'cannot redeclare block-scoped variable' errors.isolatedModules: This option prevents a few TS features which are unsafe when treating modules as isolated files.verbatimModuleSyntax: This option forces you to useimport typeandexport type, leading to more predictable behavior and fewer unnecessary imports. Withmodule: NodeNext, it also enforces you're using the correct import syntax for ESM or CJS.
Strictness
Here are the strictness options I recommend for all projects.
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true
}
}
strict: Enables all strict type checking options. Indispensable.noUncheckedIndexedAccess: Prevents you from accessing an array or object without first checking if it's defined. This is a great way to prevent runtime errors, and should really be included instrict.noImplicitOverride: Makes theoverridekeyword actually useful in classes.
Many folks recommended the strictness options in tsconfig/bases, a wonderful repo which catalogs TSConfig options. These options include lots of rules which I consider too 'noisy', like noImplicitReturns, noUnusedLocals, noUnusedParameters, and noFallthroughCasesInSwitch. I recommend you add these rules to your tsconfig.json only if you want them.
Transpiling with TypeScript
If you're transpiling your code (creating JavaScript files) with tsc, you'll want these options.
{
"compilerOptions": {
"module": "NodeNext",
"outDir": "dist"
}
}
module: Tells TypeScript what module syntax to use.NodeNextis the best option for Node.moduleResolution: NodeNextis implied from this option.outDir: Tells TypeScript where to put the compiled JavaScript files.distis my preferred convention, but it's up to you.
Building for a Library
If you're building for a library, you'll want declaration: true.
{
"compilerOptions": {
"declaration": true
}
}
declaration: Tells TypeScript to emit.d.tsfiles. This is needed so that libraries can get autocomplete on the.jsfiles you're creating.
Building for a Library in a Monorepo
If you're building for a library in a monorepo, you'll also want these options.
{
"compilerOptions": {
"declaration": true,
"composite": true,
"sourceMap": true,
"declarationMap": true
}
}
composite: Tells TypeScript to emit.tsbuildinfofiles. This tells TypeScript that your project is part of a monorepo, and also helps it to cache builds to run faster.sourceMapanddeclarationMap: Tells TypeScript to emit source maps and declaration maps. These are needed so that when consumers of your libraries are debugging, they can jump to the original source code using go-to-definition.
Not Transpiling with TypeScript
If you're not transpiling your code with tsc, i.e. using TypeScript as more of a linter, you'll want these options.
{
"compilerOptions": {
"module": "preserve",
"noEmit": true
}
}
module:preserveis the best option because it most closely mimics how bundlers treat modules.moduleResolution: Bundleris implied from this option.noEmit: Tells TypeScript not to emit any files. This is important when you're using a bundler so you don't emit useless.jsfiles.
Running in the DOM
If your code runs in the DOM, you'll want these options.
{
"compilerOptions": {
"lib": ["es2022", "dom", "dom.iterable"]
}
}
lib: Tells TypeScript what built-in types to include.es2022is the best option for stability.domanddom.iterablegive you types forwindow,documentetc.
Not Running in the DOM
If your code doesn't run in the DOM, you'll want lib: ["es2022"].
{
"compilerOptions": {
"lib": ["es2022"]
}
}
These are the same as above, but without the dom and dom.iterable typings.