$ sudo add-apt-repository ppa:otto-kesselgulasch/gimp
$ sudo apt-get update
$ sudo apt-get install gimp
Wednesday, 26 December 2018
How to install Gimp on Ubuntu 18.06
How to install Go on Nvidia Jetson TX2
$ uname -a
Linux tegra-ubuntu 4.4.38-tegra #1 SMP PREEMPT Thu May 17 00:15:19 PDT 2018 aarch64 aarch64 aarch64 GNU/Linux
To find the processor architecture we can check out the content of /proc/cpuinfo file:
$ cat /proc/cpuinfo
processor : 0
model name : ARMv8 Processor rev 3 (v8l)
BogoMIPS : 62.50
Features : fp asimd evtstrm aes pmull sha1 sha2 crc32
CPU implementer : 0x41
CPU architecture: 8
CPU variant : 0x1
CPU part : 0xd07
CPU revision : 3
processor : 3
model name : ARMv8 Processor rev 3 (v8l)
BogoMIPS : 62.50
Features : fp asimd evtstrm aes pmull sha1 sha2 crc32
CPU implementer : 0x41
CPU architecture: 8
CPU variant : 0x1
CPU part : 0xd07
CPU revision : 3
processor : 4
model name : ARMv8 Processor rev 3 (v8l)
BogoMIPS : 62.50
Features : fp asimd evtstrm aes pmull sha1 sha2 crc32
CPU implementer : 0x41
CPU architecture: 8
CPU variant : 0x1
CPU part : 0xd07
CPU revision : 3
processor : 5
model name : ARMv8 Processor rev 3 (v8l)
BogoMIPS : 62.50
Features : fp asimd evtstrm aes pmull sha1 sha2 crc32
CPU implementer : 0x41
CPU architecture: 8
CPU variant : 0x1
CPU part : 0xd07
CPU revision : 3
We can see that Jetson TX2 uses version 8 of the ARM instruction set. Luckily, Go Downloads page provides archive for ARMv8 (Downloads >> Stable Versions >> Other Ports). At the time of writing the latest version was:
go1.11.4.linux-arm64.tar.gz Archive Linux ARMv8 96MB
Upon downloading the archive and verifying its checksum we can install Go by extracting it into /usr/local directory:
tar -C /usr/local -xzf go1.11.4.linux-arm64.tar.gz
Go binaries are in /usr/local/go/bin directory and to make them available from any new terminal session we have to add and persist this path to PATH environment variable.
We have to edit bash configuration:
$ sudo gedit ~/.bashrc
export PATH=(...):/usr/local/go/bin
Go installation requires defining which local directory will be Go workspace (place with all Go repositories - source code, builds and packages). I chose it to be dev/go directory in my home directory instead of the default one which is $HOME/go. For I am using non-default workspace location I have to add another environment variable in the same bash config file:
export GOPATH=$HOME/dev/go
As I've already created Go test project on my GitHub account when I was testing Go installation on Windows we can simply clone that project. Before we do it, let's make go get use SSH URL instead of HTTPS so we don't have to change it later manually (like on Windows). To achieve this we have to change global git configuration (suggested here):
$ git config --global url.git@github.com:.insteadOf https://github.com/
Let's do the clone now:
~/dev/go$ mkdir src
~/dev/go$ cd src
~/dev/go/src$ go get github.com/BojanKomazec/go-hello-world
We now have a sample go file: ~/dev/go/src/github.com/BojanKomazec/go-hello-world/hello/hello.go.
To verify that SSH URL has been used we can execute:
~/dev/go/src/github.com/BojanKomazec/go-hello-world$ git remote get-url origin
git@github.com:BojanKomazec/go-hello-world
Let's go to hello directory and build our go file:
$ go build hello.go
This creates hello executable that we can run:
$ ./hello
hello, world
This proves that our Go installation on Jetson TX2 was successful.
Saturday, 22 December 2018
Setting up Go on Windows
Installation is straightforward:
By default, installer creates or modifies the following environment variables:
In System space:
Variable (created): GOROOT
Value: C:\Go\
Description: Go installation location.
Variable (value appended): Path
Value: C:\Go\bin
Description: Go binaries location.
Variable (created): GOPATH
Value: %USERPROFILE%\go
Description: User's go workspace path.
Variable (value appended): Path
Value: %USERPROFILE%\go\bin
Description: User's Go applications' binaries location.
Go workspace:
- a directory with two subdirectories: bin and src
- src typically contains all repositories with Go projects
- bin contains built and then installed Go application binaries
- can be set at arbitrary location; I set mine to C:\dev\go (and also set User space Path to C:\dev\go\bin)
Upon installation, C:\Go\bin contains three binaries:
- go - Tool for managing Go source code
- godoc - Documentation tool; parses Go source code - including comments - and produces documentation as HTML or plain text
- gofmt - Go source code formatter; uses tabs for indentation and blanks for alignment.
Let's see what are the command line arguments of go tool:
If we already have some Go project in some Git repository (like GitHub), we can use get command to clone the given repository:
package github.com/BojanKomazec/go-hello-world: no Go files in
C:\dev\go\src\github.com\BojanKomazec\go-hello-world
Repository is cloned to C:\dev\go\src\github.com\BojanKomazec\go-hello-world directory.
Repository shall be written without starting https:// as go get would report an error:
package https:/github.com/BojanKomazec/go-hello-world: https:/github.com/BojanKomazec/go-hello-world: invalid import path: malformed import path "https:/github.com/BojanKomazec/go-hello-world": invalid char ':'
This my repository only has .gitignore and README.md files so let's add some code. First, let's create a directory named hello and in it a go file with the following content:
C:\dev\go\src\github.com\BojanKomazec\go-hello-world\hello\hello.go:
package main
import "fmt"
func main() {
fmt.Printf("hello, world\n")
}
Building this file with:
...creates a hello.exe file in the same directory and we can run it:
hello, world
To install that build as a package, we have to run:
This deploys application binary in C:\dev\go\bin directory.
If we add, commit and then try to push hello.go file to remote repository, we'll be prompted by Git to enter our GitHub credentials as by default go get sets the https-based URL of the remote. We can verify that with:
* remote origin
Fetch URL: https://github.com/BojanKomazec/go-hello-world
Push URL: https://github.com/BojanKomazec/go-hello-world
HEAD branch: master
Remote branch:
master tracked
Local branch configured for 'git pull':
master merges with remote master
Local ref configured for 'git push':
master pushes to master (up to date)
We can set SSH-based URL by executing:
Let's verify it:
Enter passphrase for key '/c/Users/komazec/.ssh/id_rsa':
* remote origin
Fetch URL: git@github.com:BojanKomazec/go-hello-world.git
Push URL: git@github.com:BojanKomazec/go-hello-world.git
HEAD branch: master
Remote branch:
master tracked
Local branch configured for 'git pull':
master merges with remote master
Local ref configured for 'git push':
master pushes to master (up to date)
Let's now analyse code in the go source file above.
package main
func main() {
...
}
This line tells the Go compiler that the package should compile as an executable program. Its entry point will be function main(). If we were building a shared library, we would use package lib directive and there would not be main() function in the package.
...
fmt.Printf("hello, world\n")
import statement imports a package into other package. Here, we wanted to use function which prints a string onto standard output. Such function, Printf, is available in the fmt package which comes from the Go standard library. Go compiler looks for standard library packages on paths specified in GOROOT and your and third-party packages on path specified in GOPATH environment variables.
Project on GutHub:
https://github.com/BojanKomazec/go-hello-worldReferences:
golang.org: Go installation on WindowsUnderstanding Golang Packages
Package “main” and func “main”
Tuesday, 11 December 2018
Introduction to Yarn
- package manager
- developed by Facebook
- uses the same package.json as npm
- uses its own lock file - yarn.lock (not package-lock.json like npm)
- if installing it on Windows via installer, Node.js has to be installed first
- once installed re-launch terminal and type yarn -v to verify that it's installed successfully and see its version
- if you check out some project which uses yarn, you would typically first run yarn install to install all the dependencies of project
- each module has npm-based and yarn-based packages so can be installed via either dependency manager. E.g. babel-core:
- npm: npm install --save-dev @babel/core
- yarn: yarn add @babel/core --dev
Sunday, 9 December 2018
How to install JetPack 3.3 on Ubuntu 18.04 and flash Jetson TX2
- TensorRT 4.0 (ONNX model support)
- cuDNN v7.1.5 (improved TensorFlow model parsing)
These are the screenshots of the successful JetPack 3.3 installation on Ubuntu 18.04 and flashing Jetson TX2:
It takes couple of seconds for Component Manager to download repo information, do version checks and show the current state of packages:
At this point I actually stopped the installation as wanted to do flashing of TX a bit later. This is possible as Component Manager will pick up and show the current state of all packages upon JetPack installer re-launch:
Now I pressed ENTER to resume the installation.
Just like before, I verified that all has completed successfully on TX2 by running some of installed CUDA demo examples (e.g. rendering ocean surface - "OceanFFT").
Thursday, 18 October 2018
How to install Node.js on Windows
Upon installation system variable Path (in environment variables) contains a new entry:
C:\Program Files\nodejs\.
Let's see what's inside this directory:
c:\Program Files\nodejs\node_modules\npm\
c:\Program Files\nodejs\node_modules\npm\.github\
c:\Program Files\nodejs\node_modules\npm\bin\
c:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin\
c:\Program Files\nodejs\node_modules\npm\bin\npm
c:\Program Files\nodejs\node_modules\npm\bin\npm.cmd
c:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js
c:\Program Files\nodejs\node_modules\npm\bin\read-package-json.js
c:\Program Files\nodejs\node_modules\npm\changelogs\
c:\Program Files\nodejs\node_modules\npm\doc\
c:\Program Files\nodejs\node_modules\npm\html\
c:\Program Files\nodejs\node_modules\npm\lib\
c:\Program Files\nodejs\node_modules\npm\man\
c:\Program Files\nodejs\node_modules\npm\node_modules\
c:\Program Files\nodejs\node_modules\npm\scripts\
c:\Program Files\nodejs\node_modules\npm\test\
c:\Program Files\nodejs\node_modules\npm\.mailmap
c:\Program Files\nodejs\node_modules\npm\.npmignore
c:\Program Files\nodejs\node_modules\npm\AUTHORS
c:\Program Files\nodejs\node_modules\npm\configure
c:\Program Files\nodejs\node_modules\npm\LICENSE
c:\Program Files\nodejs\node_modules\npm\Makefile
c:\Program Files\nodejs\node_modules\npm\npmrc
c:\Program Files\nodejs\node_modules\npm\make.bat
c:\Program Files\nodejs\node_modules\npm\cli.js
c:\Program Files\nodejs\node_modules\npm\package.json
c:\Program Files\nodejs\node_modules\npm\CHANGELOG.md
c:\Program Files\nodejs\node_modules\npm\CONTRIBUTING.md
c:\Program Files\nodejs\node_modules\npm\README.md
c:\Program Files\nodejs\node_modules\npm\.travis.yml
c:\Program Files\nodejs\node_modules\npm\appveyor.yml
c:\Program Files\nodejs\npm
c:\Program Files\nodejs\nodevars.bat
c:\Program Files\nodejs\npm.cmd
c:\Program Files\nodejs\node.exe
c:\Program Files\nodejs\node_etw_provider.man
c:\Program Files\nodejs\node_perfctr_provider.man
How to check installed version?
v10.7.0
Thursday, 11 October 2018
Introduction to TSLint
---
TSLint is a TypeScript linter.
Source code of the project which uses TSLint is on GitHub.
Installation
Let's install it as a development dependency:+ tslint@5.11.0
added 40 packages from 20 contributors and audited 51 packages in 5.225s
found 0 vulnerabilities
CLI Usage
Let's run tslint with no arguments specified, from the project's root directory:No files specified. Use --project to lint a project folder.
Let's find what is --project argument and see what are the other command line arguments:
Usage: [options]
Options:
-v, --version output the version number
-c, --config [config] configuration file
-e, --exclude <exclude> exclude globs from path expansion (default: [])
--fix fixes linting errors for select rules (this may overwrite linted files)
--force return status code 0 even if there are lint errors
-i, --init generate a tslint.json config file in the current working directory
-o, --out [out] output file
--outputAbsolutePaths whether or not outputted file paths are absolute
-r, --rules-dir [rules-dir] rules directory
-s, --formatters-dir [formatters-dir] formatters directory
-t, --format [format] output format (prose, json, stylish, verbose, pmd, msbuild, checkstyle, vso, fileslist, codeFrame)
--test test that tslint produces the correct output for the specified directory
-p, --project [project] tsconfig.json file
--type-check (deprecated) check for type errors before linting the project
-h, --help output usage information
tslint accepts the following commandline options:
-c, --config:
The location of the configuration file that tslint will use to
determine which rules are activated and what options to provide
to the rules. If no option is specified, the config file named
tslint.json is used, so long as it exists in the path.
The format of the file is { rules: { /* rules list */ } },
where /* rules list */ is a key: value comma-separated list of
rulename: rule-options pairs. Rule-options can be either a
boolean true/false value denoting whether the rule is used or not,
or a list [boolean, ...] where the boolean provides the same role
as in the non-list case, and the rest of the list are options passed
to the rule that will determine what it checks for (such as number
of characters for the max-line-length rule, or what functions to ban
for the ban rule).
-e, --exclude:
A filename or glob which indicates files to exclude from linting.
This option can be supplied multiple times if you need multiple
globs to indicate which files to exclude.
--fix:
Fixes linting errors for select rules. This may overwrite linted files.
--force:
Return status code 0 even if there are any lint errors.
Useful while running as npm script.
-i, --init:
Generates a tslint.json config file in the current working directory.
-o, --out:
A filename to output the results to. By default, tslint outputs to
stdout, which is usually the console where you're running it from.
--outputAbsolutePaths:
If true, all paths in the output will be absolute.
-r, --rules-dir:
An additional rules directory, for user-created rules.
tslint will always check its default rules directory, in
node_modules/tslint/lib/rules, before checking the user-provided
rules directory, so rules in the user-provided rules directory
with the same name as the base rules will not be loaded.
-s, --formatters-dir:
An additional formatters directory, for user-created formatters.
Formatters are files that will format the tslint output, before
writing it to stdout or the file passed in --out. The default
directory, node_modules/tslint/build/formatters, will always be
checked first, so user-created formatters with the same names
as the base formatters will not be loaded.
-t, --format:
The formatter to use to format the results of the linter before
outputting it to stdout or the file passed in --out. The core
formatters are prose (human readable), json (machine readable)
and verbose. prose is the default if this option is not used.
Other built-in options include pmd, msbuild, checkstyle, and vso.
Additional formatters can be added and used if the --formatters-dir
option is set.
--test:
Runs tslint on matched directories and checks if tslint outputs
match the expected output in .lint files. Automatically loads the
tslint.json files in the directories as the configuration file for
the tests. See the full tslint documentation for more details on how
this can be used to test custom rules.
-p, --project:
The path to the tsconfig.json file or to the directory containing
the tsconfig.json file. The file will be used to determine which
files will be linted. This flag also enables rules that require the
type checker.
--type-check:
(deprecated) Checks for type errors before linting a project.
--project must be specified in order to enable type checking.
-v, --version:
The current version of tslint.
-h, --help:
Prints this help message.
Let's specify path to tsconfig.json file (which is in the project's root where we're executing tsling from):
no-unused-variable is deprecated. Since TypeScript 2.9. Please use the built-in compiler checks instead.
Could not find implementations for the following rules specified in the configuration:
label-undefined
no-duplicate-key
no-trailing-comma
no-unreachable
use-strict
Try upgrading TSLint and/or ensuring that you have all necessary custom rules installed.
If TSLint was recently upgraded, you may have old rules configured which need to be cleaned up.
ERROR: C:/dev/github/demo-typescript/src/index.ts[3, 5]: expected variable-declaration: 'dayTimeGreetingGenerator' to have a typedef
ERROR: C:/dev/github/demo-typescript/src/index.ts[5, 10]: expected call-signature: 'createPersonalGreeting' to have a typedef
ERROR: C:/dev/github/demo-typescript/src/index.ts[9, 5]: expected variable-declaration: 'user' to have a typedef
ERROR: C:/dev/github/demo-typescript/src/index.ts[12, 5]: expected variable-declaration: 'greeting' to have a typedef
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreeting.ts[2, 19]: ' should be "
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreeting.ts[3, 21]: ' should be "
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreeting.ts[4, 19]: ' should be "
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreetingGenerator.ts[1, 57]: trailing whitespace
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreetingGenerator.ts[5, 25]: expected nospace before colon in call-signature
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreetingGenerator.ts[7, 33]: ' should be "
ERROR: C:/dev/github/demo-typescript/src/module/greetingGenerator.ts[1, 18]: interface name must start with a capitalized I
ERROR: C:/dev/github/demo-typescript/src/module/greetingGenerator.ts[2, 18]: expected nospace before colon in call-signature
Good, linting works!
Configuration
If we run:
..\demo-typescript>npx tslint --init
...tslint creates TSLint configuration file - tslint.json in the current directory. tslint.json for now only has its default content:
"defaultSeverity": "error",
"extends": [
"tslint:recommended"
],
"jsRules": {},
"rules": {},
"rulesDirectory": []
}
After having TSLint config file, its output contains only linting messages:
ERROR: C:/dev/github/demo-typescript/src/index.ts[3, 5]: Identifier 'dayTimeGreetingGenerator' is never reassigned; use 'const' instead of 'let'.
ERROR: C:/dev/github/demo-typescript/src/index.ts[5, 39]: expected nospace before colon in parameter
ERROR: C:/dev/github/demo-typescript/src/index.ts[9, 5]: Identifier 'user' is never reassigned; use 'const' instead of 'let'.
ERROR: C:/dev/github/demo-typescript/src/index.ts[12, 5]: Identifier 'greeting' is never reassigned; use 'const' instead of 'let'.
ERROR: C:/dev/github/demo-typescript/src/index.ts[14, 1]: Calls to 'console.log' are not allowed.
ERROR: C:/dev/github/demo-typescript/src/index.ts[14, 23]: file should end with a newline
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreeting.ts[2, 19]: ' should be "
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreeting.ts[3, 21]: ' should be "
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreeting.ts[4, 19]: ' should be "
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreeting.ts[4, 33]: Missing trailing comma
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreeting.ts[5, 2]: file should end with a newline
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreetingGenerator.ts[1, 57]: trailing whitespace
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreetingGenerator.ts[2, 1]: Import sources within a group must be alphabetized.
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreetingGenerator.ts[5, 25]: expected nospace before colon in call-signature
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreetingGenerator.ts[6, 20]: expected nospace before colon in variable-declaration
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreetingGenerator.ts[7, 21]: expected nospace before colon in variable-declaration
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreetingGenerator.ts[7, 33]: ' should be "
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreetingGenerator.ts[8, 21]: missing whitespace
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreetingGenerator.ts[17, 3]: file should end with a newline
ERROR: C:/dev/github/demo-typescript/src/module/greetingGenerator.ts[1, 18]: interface name must start with a capitalized I
ERROR: C:/dev/github/demo-typescript/src/module/greetingGenerator.ts[2, 18]: expected nospace before colon in call-signature
ERROR: C:/dev/github/demo-typescript/src/module/greetingGenerator.ts[3, 2]: file should end with a newline
We can now add linting to TS build task in package.json. TSLint documentation says "Please ensure that the TypeScript source files compile correctly before running the linter." and we'll place linting after transpilation:
If we run npm task we'll see that TSLint process exited with error code:
> demo-typescript@1.0.0 build-ts C:\dev\github\demo-typescript
> tsc && tslint -p ./
ERROR: C:/dev/github/demo-typescript/src/index.ts[3, 5]: Identifier 'dayTimeGreetingGenerator' is never reassigned; use 'const' instead of 'let'.
ERROR: C:/dev/github/demo-typescript/src/index.ts[5, 39]: expected nospace before colon in parameter
ERROR: C:/dev/github/demo-typescript/src/index.ts[9, 5]: Identifier 'user' is never reassigned; use 'const' instead of 'let'.
ERROR: C:/dev/github/demo-typescript/src/index.ts[12, 5]: Identifier 'greeting' is never reassigned; use 'const' instead of 'let'.
ERROR: C:/dev/github/demo-typescript/src/index.ts[14, 1]: Calls to 'console.log' are not allowed.
ERROR: C:/dev/github/demo-typescript/src/index.ts[14, 23]: file should end with a newline
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreeting.ts[2, 19]: ' should be "
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreeting.ts[3, 21]: ' should be "
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreeting.ts[4, 19]: ' should be "
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreeting.ts[4, 33]: Missing trailing comma
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreeting.ts[5, 2]: file should end with a newline
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreetingGenerator.ts[1, 57]: trailing whitespace
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreetingGenerator.ts[2, 1]: Import sources within a group must be alphabetized.
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreetingGenerator.ts[5, 25]: expected nospace before colon in call-signature
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreetingGenerator.ts[6, 20]: expected nospace before colon in variable-declaration
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreetingGenerator.ts[7, 21]: expected nospace before colon in variable-declaration
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreetingGenerator.ts[7, 33]: ' should be "
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreetingGenerator.ts[8, 21]: missing whitespace
ERROR: C:/dev/github/demo-typescript/src/module/dayTimeGreetingGenerator.ts[17, 3]: file should end with a newline
ERROR: C:/dev/github/demo-typescript/src/module/greetingGenerator.ts[1, 18]: interface name must start with a capitalized I
ERROR: C:/dev/github/demo-typescript/src/module/greetingGenerator.ts[2, 18]: expected nospace before colon in call-signature
ERROR: C:/dev/github/demo-typescript/src/module/greetingGenerator.ts[3, 2]: file should end with a newline
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! demo-typescript@1.0.0 build-ts: `tsc && tslint -p ./`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the demo-typescript@1.0.0 build-ts script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\komazec\AppData\Roaming\npm-cache\_logs\2018-10-11T16_35_49_031Z-debug.log
Having TSLint exit with Exit status 2 is expected as TSLint reported suggestions with ERROR severity and its documentation says that status 2 indeed means "Linting failed with one or more rule violations with severity error".
We can see that linter complaints about using single quotation marks instead of double ones (' should be "). TS coding conventions actually prefers single quotes so we want to change the rule for TSLinter. The rule we want to change in tslint.json is quotemark:
"rules": {
"quotemark": [true, "single"]
},
...
If we run tslint again, we'll see that it does not emit ' should be " messages anymore.
VSCode Extension
TSLintIt will start showing errors/suggestions as soon as plugin is installed and VSCode reloaded.
Disabling TSLint Errors
To disable some error in the next line only:
E.g. for some line I got the following error:
Expected a 'for-of' loop instead of a 'for' loop with this simple iteration (prefer-for-of) tslint(1)
To disable that error the following line should be added before that code line:
// tslint:disable-next-line:prefer-for-of
TSLint rule flags
References:
https://palantir.github.io/tslint/
tslint says calls to console.log are not allowed - How do I allow this?
Introduction to TypeScript
Let's first initialize our Node project:
Installation
TypeScript has a command-line compiler which transforms TypeScript code into JavaScript. It comes in a form of a Node package named typescript. Let's install it as a development dependency:
npm notice created a lockfile as package-lock.json. You should commit this file.
+ typescript@3.1.1
added 1 package from 1 contributor and audited 1 package in 1.318s
found 0 vulnerabilities
package.json now contains:
...
"devDependencies": {
"typescript": "^3.1.1"
}
}
Because we installed TypeScript for the current project only (not globally), TypeScript compiler, tsc, is not available from the command line. We can run it in three ways:
- directly as ./node_modules/.bin/tsc
- via npx tool,
- via npm run tsc if we add it as a script in package.json as:
"scripts": {
"tsc":"tsc"
...
}
...
How to install declaration files for npm packages I am using?
From DefinitelyTyped/DefinitelyTyped: The repository for high quality TypeScript type definitions.
This is the preferred method
npm install --save-dev @types/node
The types should then be automatically included by the compiler.
For an NPM package "foo", typings for it will be at "@types/foo".
typescript - How do I decide whether @types/* goes into `dependencies` or `devDependencies`? - Stack Overflow
TypeScript Compiler
Let's see what are the command line arguments and options of tsc:
Version 3.1.1
Syntax: tsc [options] [file...]
Examples: tsc hello.ts
tsc --outFile file.js file.ts
tsc @args.txt
tsc --build tsconfig.json
Options:
-h, --help Print this message.
-w, --watch Watch input files.
--all Show all compiler options.
-v, --version Print the compiler's version.
--init Initializes a TypeScript project and creates a tsconfig.json file.
-p FILE OR DIRECTORY, --project FILE OR DIRECTORY Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'.
-b, --build Build one or more projects and their dependencies, if out of date
--pretty Stylize errors and messages using color and context (experimental).
-t VERSION, --target VERSION Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'.
-m KIND, --module KIND Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'.
--lib Specify library files to be included in the compilation.
'es5' 'es6' 'es2015' 'es7' 'es2016' 'es2017' 'es2018' 'esnext' 'dom' 'dom.iterable' 'webworker' 'webworker.importscripts' 'scripthost' 'es2015.core' 'es2015.collection' 'es2015.generator' 'es2015.iterable' 'es2015.promise' 'es2015.proxy' 'es2015.reflect' 'es2015.symbol' 'es2015.symbol.wellknown' 'es2016.array.include' 'es2017.object' 'es2017.sharedmemory' 'es2017.string' 'es2017.intl' 'es2017.typedarrays' 'es2018.intl' 'es2018.promise' 'es2018.regexp' 'esnext.array' 'esnext.symbol' 'esnext.asynciterable' 'esnext.intl'
--allowJs Allow javascript files to be compiled.
--jsx KIND Specify JSX code generation: 'preserve', 'react-native', or 'react'.
-d, --declaration Generates corresponding '.d.ts' file.
--declarationMap Generates a sourcemap for each corresponding '.d.ts' file.
--sourceMap Generates corresponding '.map' file.
--outFile FILE Concatenate and emit output to single file.
--outDir DIRECTORY Redirect output structure to the directory.
--removeComments Do not emit comments to output.
--noEmit Do not emit outputs.
--strict Enable all strict type-checking options.
--noImplicitAny Raise error on expressions and declarations with an implied 'any' type.
--strictNullChecks Enable strict null checks.
--strictFunctionTypes Enable strict checking of function types.
--strictPropertyInitialization Enable strict checking of property initialization in classes.
--noImplicitThis Raise error on 'this' expressions with an implied 'any' type.
--alwaysStrict Parse in strict mode and emit "use strict" for each source file.
--noUnusedLocals Report errors on unused locals.
--noUnusedParameters Report errors on unused parameters.
--noImplicitReturns Report error when not all code paths in function return a value.
--noFallthroughCasesInSwitch Report errors for fallthrough cases in switch statement.
--types Type declaration files to be included in compilation.
--esModuleInterop Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'.
@<file> Insert command line options and files from a file.
Compiling
Let's add to the project some TypeScript file.
..\demo-typescript\src\index.ts:
return "Hello, " + person;
}
let user = "Bojan";
let greeting = greeter(user);
console.log(greeting);
Let's follow an example from tsc --help in order to get TS code compiled into JavaScript:
After this command is executed build/index.js file is created and it looks like this:
return "Hello, " + person;
}
var user = "Bojan";
var greeting = greeter(user);
console.log(greeting);
We can run it with Node.js:
Hello, Bojan
It is not possible to specify compiling files from entire directory via command line arguments - all files have to be explicitly listed. This and also listing all arguments in the command line is not practical. Solution for this is specifying all options in the configuration file and instructing tsc to read everything from it.
Configuration
TypeScript transpiler uses a config file tsconfig.json. To create , use:
message TS6071: Successfully created a tsconfig.json file.
---
If we installed TypeScript as a local package (and possibly as dev dependency) via:
$ npm install typescript --save-dev
...and if we added to package.json:
"scripts": {
...
"tsc": "tsc"
},
...then we can call tsc init via:
$ npm run tsc -- --init
---
Default content of tsconfig.json is:
"compilerOptions": {
/* Basic Options */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
}
}
If we execute
...tsc will compile all .ts files in the project and place matching .js files next to .ts files.
To specify output directory (named e.g. "bundle", "dist" or "build") into which we want output structure to be placed in, we can set in config file:
npx tsc will now output all .js files (preserving their original directory tree) in the bundle directory.
Let's now add build and start scripts to package.json so we don't have to use npx and run tools manually but follow the common approach - use npm as the task runner:
..\demo-typescript\package.json:
...
"build-ts" : "tsc",
"start" : "node bundle/index.js"
},
Let's build the app:
> demo-typescript@1.0.0 build-ts ..\demo-typescript
> tsc
Let's run the app:
..\demo-typescript>npm run start
> demo-typescript@1.0.0 start ..\demo-typescript
> node bundle/index.js
Hello, Bojan
I used name build-ts for script which runs tsc but this script is usually named just tsc.
In case you get an error like this:
$ npm run tsc
...
error TS18003: No inputs were found in config file '/path/to/tsconfig.json'. Specified 'include' paths were '["**/*"]' and 'exclude' paths were '[]'.
Makes sure you have .ts (not .js!) files in the directory (or its subdirectories) where tsconfig.json resides.
In case you get an error like this:
$ npm run tsc
> my_app@1.0.0 tsc /home/bojan/../my_app
> tsc
node_modules/@types/babel__template/index.d.ts:16:28 - error TS2583: Cannot find name 'Set'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
16 placeholderWhitelist?: Set<string>;
~~~
Found 1 error.
...simply change tsconfig.json to contain:
"lib": ["es2015"],
If you get error like this:
$ npm run tsc
> my_app@1.0.0 tsc /home/bojan/../my_app
> tsc
src/main.ts:1:1 - error TS2584: Cannot find name 'console'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'.
1 console.log("Hello, world")
~~~~~~~
Found 1 error.
...follow the suggestion and add 'dom' to the lib property:
"lib": ["es2015", "dom"],
Error example:
$ npm run tsc
> my_app@1.0.0 tsc /home/bojan/../my_app
> tsc
tsconfig.json:5:5 - error TS6082: Only 'amd' and 'system' modules are supported alongside --outFile.
5 "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
~~~~~~~~
tsconfig.json:13:5 - error TS6082: Only 'amd' and 'system' modules are supported alongside --outFile.
13 "outFile": "./build/wpsync.js", /* Concatenate and emit output to single file. */
~~~~~~~~~
Found 2 errors.
In "module": "commonjs", replace commonjs with system:
xxx
Module Generation
module property in tsconfig.json can be set to one of the following values: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'.
If we want to make tsc bundling build output into a single file we have to use outFile property but this in turn requires module to be set to either amd or system.
Asynchronous Module Definition requires RequireJS
If modules is set to amd (Asynchronous Module Definition [Wikipedia]) then our project needs to use library which implements AMD e.g. RequireJS.
This is the example of the tsc output in case when module is set to amd:
"use strict";
define("src/greeter", ["require", "exports"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function greeter(name) {
return "Hello, " + name;
}
exports.greeter = greeter;
});
define("src/main", ["require", "exports", "src/greeter"], function (require, exports, greeter_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
console.log(greeter_1.greeter('Bojan'));
});
If we try to run it without setting RequireJS beforehand:
$ node app.js
...we'll get an error:
ReferenceError: define is not defined
Uncaught ReferenceError: define is not defined typescript
How to run a TypeScript app compiled into a single file with AMD modules?
RequireJS is module loader used mostly in web application and is not native for Node.js applications.
System requires SystemJS
If modules is set to system then our project needs to use SystemJS.
This is the example of the tsc output in case when module is set to system:
"use strict";
System.register("src/greeter", [], function (exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
function greeter(name) {
return "Hello, " + name;
}
exports_1("greeter", greeter);
return {
setters: [],
execute: function () {
}
};
});
System.register("src/main", ["src/greeter"], function (exports_2, context_2) {
"use strict";
var greeter_1;
var __moduleName = context_2 && context_2.id;
return {
setters: [
function (greeter_1_1) {
greeter_1 = greeter_1_1;
}
],
execute: function () {
console.log(greeter_1.greeter('Bojan'));
}
};
});
If we try to run it without setting SystemJS beforehand:
$ node app.js
...we'll get an error:
ReferenceError: System is not defined
How do I fix “ReferenceError: System is not defined” when running script from command line?
If we don't want to use RequireJS or SystemJS then we can't use tsc to compile our TS code into a single file bundle. We need to use some bundler...like Rollup.js. Seems that the answer How do I compile my TypeScript code for Node.js to one file? is still actual.
CommonJS
Default value for module property is commonjs. This means that - CommonJS is gonna be used and CommonJS is a "native" module loader for Node.js applications.
Syntax
Variables
TIP: Follow const-correctness and always declare variable as const when its value is not supposed to be changed. Good practice is to make variable const instantly and change it to non-const later, when proved to be necessary.
Functions
Function Arguments
function foo(n: number){}
Promises
This is a signature of Promise constructor. It takes a function (named executor) which itself takes two functions (callbacks), named resolve and reject:Promise
(
executor:
(
resolve: (value?: void | PromiseLike<void> | undefined) => void,
reject: (reason?: any) => void
) => void
): Promise<void>
TypeScript Deep Dive: Promise
The return type of an async function or method must be the global Promise<T> type:
- the return type of an async function is a promise
- It's like how async functions in .NET need be declared as returning a Task<T> but the actual code is written as though it returns T directly. The async and await keywords are just sugar for automatic promise wrapping/unwrapping.
- await does not make a function synchronous. From the point of view of the topmost (non-awaiting) caller it behaves like a return and the function resumes “in the background”, controlled by the event loop.
async-await idiom
Modules
.ts file becomes a module if it exports types, enums, functions, classes or interfaces.
In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module. [https://www.typescriptlang.org/docs/handbook/modules.html]
Export syntax:
...
}
export function MyFunction() : T {
...
}
export enum MyEnum {
...
}
Import syntax:
can be replaced with shorter form:
If you use require in your .ts code:
var config = require("./config")
...you might get the following TS compiler error:
Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig.ts(2591)
This is because TS compiler knows only about "classic" browser/front-end JavaScript and require() is not part of it but is available in Node.js.
Solution
Client on node: Uncaught ReferenceError: require is not defined
const config = require('./config')
...might make tsc generate the following informational message:
'require' call may be converted to an import. ts(80005)
After conversion the code line becomes:
import config from './config';
If we had:
import config from './config/config.json';
Cannot find module './config/config.json'. Consider using '--resolveJsonModule' to import module with '.json' extension. ts(2732)
request
The following line:const request = require('request');
makes TSLint to complain with:
require statement not part of an import statement (no-var-requires) tslint(1)
Typescript : require statement not part of an import statement
Rule: no-var-requires
If we change it to:
import request = require('request');
...then TS compiler complaints with:
Could not find a declaration file for module 'request'. '/home/bojan/dev/github/demo-typescript/node_modules/request/index.js' implicitly has an 'any' type.
Try `npm install @types/request` if it exists or add a new declaration (.d.ts) file containing `declare module 'request';`ts(7016)
Luckily, npm package we want to use does provide type definitions: https://www.npmjs.com/package/@types/request
Installing @types package makes TS error message to disappear:
$ npm install @types/request --save-dev
Read more about type definition files (.d.ts) here:
How do I add TypeScript types to a JavaScript module without switching to TypeScript?
By looking the node_modules/@types/request/index.d.ts file we can now examine the TS types in the API of that package. This is very useful as now we don't have to use any for types used in package's API (e.g. callbacks) but regular TS types.
TypeScript + Node.js + Rollup:
tsconfig.json:"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
Importing CommonJS dependencies
If I import CommonJS package e.g. request as:
import request = require("request");
at Object.<anonymous> (/home/bojan/dev/.../my-app/build/app.js:16:1)
at Module._compile (internal/modules/cjs/loader.js:805:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:816:10)
at Module.load (internal/modules/cjs/loader.js:672:32)
at tryModuleLoad (internal/modules/cjs/loader.js:612:12)
at Function.Module._load (internal/modules/cjs/loader.js:604:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:868:12)
at internal/main/run_main_module.js:21:11
If I have:
import request from "request";
This makes compile error:
(!) Unresolved dependencies, request (imported by index.ts)
...while transpiled output contains:
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var request = _interopDefault(require('request'));
After installing rollup-plugin-node-resolve
npm i rollup-plugin-node-resolve --save-dev
...and adding resolve() to the list of plugins in Rollup config, building errors again:
[!] Error: 'default' is not exported by node_modules/request/index.js
If I use named import:
import { request } from "request";
...the error message changes to:
[!] Error: 'request' is not exported by node_modules/request/index.js
Interfaces
What's the difference between “declare class” and “interface” in TypeScript:
TypeScript Deep Dive: Interfaces
How can I create an object based on an interface file definition in TypeScript?
Classes
If class D derives from class B, use keyword extends:
...
}
...
}
Type assertion
TBC...
Typescript: cast an object to other type. How? And instanceof or typeof?
Unit Testing
How to write unit testing for Angular / TypeScript for private methods with Jasmine
References:
http://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.htmlhttps://www.typescriptlang.org/docs/handbook/tsconfig-json.html
Style guide (basarat's personal)
Microsoft's TS Coding guidelines
https://www.quora.com/topic/TypeScript
Typescript. The bad, the worse, and the ugly.
JavaScript - TypeScript: Making .NET Developers Comfortable with JavaScript (2013)
Configuring TypeScript compiler
How to run typescript compiler as a package.json script without grunt or gulp?