- Installation (“global”,
-g
):<sudo> npm install typescript -g --force
- Version check:
tsc -v
- Possible uninstallation:
npm uninstall typescript -g
- Installation (“local”): creation of
package.json
file withnpm init
(name
andversion
are mandatory keys in resultingpackage.json
file)npm install typescript -D
- Possible installation of native interpreter:
npm install -D ts-node
(run as follows:npx ts-node
)
package.json
file (example){ "author": "Franck Barbier", "name": "Palindrome", "version": "1.0.0", … "main": "js/Palindrome.js", // i.e., 'require("Palindrome");'... "typings": "js/Palindrome.d.ts", // Tell where homemade types are declared for future reuse... "scripts": { "configuration": "npx tsc --showConfig", // Local version... "compilation": "npx tsc", "execution": "node js/Palindrome.js", // Does not work for the browser! "initialization": "npx tsc --init" // Creation of 'tsconfig.json' file from scratch... }, "devDependencies": { "ts-node": "^10.9.1", // Optional... "typescript": "^4.9.5" } }
What are the available scripts?
npm run
Check configuration
npm run configuration
Creation of
tsconfig.json
file from scratchnpm run initialization
Compilation
# Caution: location of source files with .ts suffix must be set up: npm run compilation
Execution (or run within browser based on Web server)
# Node.js only: npm run execution
Otherwise, direct compilation may occur as follows:
tsc Palindrome.ts <compilation options>
. For example,tsc Palindrome.ts --watch
(-w
) compilation option installs a daemon, which re-launches compilation at source file modification time.
tsconfig.json
file (example){ "compilerOptions": { "declaration": true, // See also '"typings": "js/Palindrome.d.ts",' in 'package.json'... // "emitDeclarationOnly": true, "module": "CommonJS", // Chosen module syntax (e.g., 'import', 'export'...) in JavaScript... "moduleResolution": "node", // How to resolve module dependencies (default is "node", "classic" is legacy) "outDir": "js", "sourceMap": false, // Debug issues... "target": "ES5" // Targeted JavaScript version, e.g., 'let x = y ** z;' -> JavaScript 7... }, "exclude": [ "node_modules" // This is default option, so no need anyway... ], "files": [ "ts/Palindrome.ts" // Plus possible comma-separated list of other files to compile... ] }
Rule(s)
- TypeScript uses the
tsconfig.json
file to configure compilation options and how TypeScript-related files are managed.- Source files to be compiled are found through the
files
(imported source files withimport
do not need to appear) and/orinclude
keys.Example (source files in the
ts
directory, recursively)"include": [ "ts/**/*" ],
Rule(s)
- moduleResolution is the method TypeScript applies for realizing
export
andimport
statements at compilation time. This is mainly a way of searching for imported modules in directories and resolving possible conflicts linked to the inclusion of multiple library versions.- module (code generation for module system) is the syntax for the generated JavaScript code (execution time).
"CommonJS"
value benefits from being the more simple way (for Node.js especially) while"ESNext"
is the very last JavaScript facility.- target is the generated syntax for the JavaScript version used for execution.
"ES2021"
is a good option.See also here…
Compilation-time code control
Rule(s)
noImplicitAny
imposes that variables have explicit types.Example (
tsconfig.json
file and later on TypeScript code)"noImplicitAny": true,
declare const dat: any; // 'any' is imposed by '"noImplicitAny": true'
Note that dat.gui is a Google library, which has a TypeScript support for type checking; a better way is then reusing such a support as follows.
npm install @types/dat.gui -D
Rule(s)
skipLibCheck
rules the way type declaration files of libraries are checked. Library compilation may raise errors whose control does not really matter."skipLibCheck": true,
skips such errors while local code remains under strict control.Example (
tsconfig.json
file)"skipLibCheck": true,
Rule(s)
suppressImplicitAnyIndexErrors
rules the way indexed variables like arrays and common objects are checked.Example (PURE JavaScript)
// window.splash-screen.enable('circular'); // Dash in 'splash-screen' creates a bug... window['splash-screen'].enable('circular'); // Right way in JavaScript
Example (
tsconfig.json
file and later on TypeScript code)"suppressImplicitAnyIndexErrors": true,
// '"suppressImplicitAnyIndexErrors": true,' is required (otherwise compilation error): window['splash-screen'].enable('circular');
Rule(s)
sourceMap
allows the generation of files as mappings between TypeScript source files and JavaScript runtime files. Typically, at debugging time, error-prone lines of code in JavaScript have counterparts in TypeScript so that debuggers trace and point out error origins.Example (
tsconfig.json
file)"sourceMap": true,
Rule(s)
allowJs
(here… See alsocheckJs
) set totrue
allows the “compilation” of JavaScript and then the smooth migration from JavaScript to TypeScript.strict
(here…) set totrue
activates the strongest mode of type checking encompassing all clustered type checking options asnoImplicitAny
,suppressImplicitAnyIndexErrors
,strictPropertyInitialization
…Example (
tsconfig.json
complete file){ "compilerOptions": { "baseUrl": ".", // https://www.typescriptlang.org/docs/handbook/module-resolution.html#additional-module-resolution-flags // https://stackoverflow.com/questions/43281741/how-to-use-paths-in-tsconfig-json: "paths": { "GLTFLoader": ["three.js-r115/examples/jsm/loaders/GLTFLoader"], // From "baseUrl" "Three": ["three.js-r115/src/Three"] // From "baseUrl" }, "module": "ES6", // Based on ES6 'import', 'export'... "moduleResolution": "node", // Required by Three.js (https://www.typescriptlang.org/docs/handbook/module-resolution.html#how-typescript-resolves-modules) "outDir": "js", // Where to generate JavaScript files... "sourceMap": true, // For debugging... "strict": true, // Strongest type checking... "target": "ES6", // Required by Three.js... "traceResolution": true }, "include": [ // Source files relative to the base URL: // '.ts', '.tsx', and '.d.ts' by default: "ts/**/*" // '*' matches zero or more characters (excluding directory separators) AND '**/' recursively matches any subdirectory... ] }
package.json
file)Note:
-D
and--save-dev
are the same and mean dev. dependency.npm install @types/node --save-dev
{ … "devDependencies": { "typescript": "^4.9.5", "@types/node": "^18.15.1" // Node.js dev. based on TypeScript… } }
tsconfig.json
file)TypeScript searches type declaration files (e.g.,
index.d.ts
) of external libraries innode_modules/@types
. ThetypeRoots
(here…) andtypes
(here…) compiler options allow some customization.npm install --save-dev @cloudflare/workers-types@latest
"compilerOptions": { … "typeRoots": [ "ts/typings", // Non-Typescript library, say "L": create 'L.d.ts' file in 'typings' directory with 'declare module "L";' inside... "node_modules/@types" // By default, it must be "regenerated"! ] "types": ["@cloudflare/workers-types"] },
references
flag
here…
Code may be componentized in self-contained TypeScript sub-projects using
references
.{ "compilerOptions": { // common "skipLibCheck": true, "sourceMap": true, "target": "ES2021", "typeRoots": [ "./ts/typings", "./node_modules/@types" ] }, "files": [], // To stop accidental compilation without '--build' -> everything is compiled in the root directory... "references": [ // https://stackoverflow.com/questions/64626846/typescript-tsc-not-picking-up-tsconfig-json-inside-a-subdirectory { "path": "./ts" // frontend }, { "path": "./ts/backend" } ] }
npx tsc --build
is then the required command for component-by-component compilation provided that sub-projects compilation options relate to roottsconfig.json
file as follows.{ // frontend "extends": "../tsconfig.json", "compilerOptions": { "module": "ES6", "moduleResolution": "Node", "outDir": "../dist", "rootDir": ".", "strict": true }, "exclude": ["./backend"], "include": [ "./**/*" ] }
Sub-project compilation may occurs as follows:
npx tsc -b ts
for frontend andnpx tsc -b ts/backend
for backend. Note that thecomposite
flag set totrue
is the way to the management of sub-project dependencies…
- Installation
npm install --save-dev webpack
- CLI installation
npm install --save-dev webpack-cli
- Version:
webpack version
- Help:
webpack help
- Beyond JavaScript code packaging, webpack proposes a specific support for TypeScript (here…).
ts-loader
is a key component of this support:npm install --save-dev ts-loader
- Configuration file creation:
touch DMiNer.config.js
- Test configuration (after populating):
webpack configtest DMiNer.config.js
const path = require('path'); module.exports = { devtool: 'source-map', entry: './ts/DMiNer.ts', mode: 'development', module: { rules: [ { test: /\.css$/i, use: ["style-loader", "css-loader"] }, { use: 'ts-loader', exclude: /node_modules/ } ], }, // optimization: { // minimize: true // }, output: { filename: 'DMiNer.js', path: path.resolve(__dirname, 'js'), }, resolve: { extensions: [".ts", ".js"] // modules: ['node_modules', 'X'] // Places to look for modules... } };
- Installation:
<sudo> npm install browserify -g
- Test:
browserify -h
- Installation of browserify-shim in local mode:
<sudo> npm install -D browserify-shim
- Version check:
cordova -v
- Update:
<sudo> npm install cordova@latest -g
- For an app.:
cordova requirements
(in devoted Apache Cordova directory)- For an app.: installation of
ios-deploy
:<sudo> npm install --unsafe-perm ios-deploy -g