A collection of code-snippets and useful info essential for web development.
-
init new npm
-package: npm init -y
-
install TypeScript-compiler: npm i typescript --save-dev
-
init TypeScript: npx tsc --init
-
add two scripts to package.json
:
- the
build
-script compiles all the files, whereas the build:check
command only checks compileability without actually compiling and creating the js-files.
"scripts": {
"build": "tsc",
"build:check": "tsc --noEmit"
},
-
Add "declaration": true
to the compilerOptions
of your tsconfig.json
. This tells TypeScript to emit an .d.ts
definitions file along with your compiled JavaScript.
-
Add "types": "index.d.ts"
to your package.json
. When other people import your library, this tells the TypeScript compiler where to look for your library’s types. The filename of your .d.ts
file will be the same as your main entry point. So, for example in your package.json
you’ll want to have something like this in there:
"main": "dist/index.js",
"types": "index.d.ts"
-
Set outDir
in tsconfig.jsin
to "outDir": "./dist"
. This specifies an output folder for all emitted files.
-
.gitignore
and .npmignore
- We don’t want to track compiled JavaScript files in our git repository, so add
dist
to the .gitignore
file. - We do, however, want them sent to NPM when we publish, so create an empty
.npmignore
file (maybe add /node_modules
there, or simply make it a copy of your .gitignore
file just without the ignore for the dist
folder). - If you don’t have an
.npmignore
, NPM will automatically exclude gitignored files from being published. Having an npmignore file overwrites this behavior.
-
Add "exclude"
object, if you want to exclude folders from the compilation process:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"lib": ["es2017", "es7", "es6", "dom"],
"declaration": true,
"outDir": "dist",
"strict": true,
"esModuleInterop": true
},
"exclude": ["node_modules", "dist", "utils/userLanguage.ts"]
}
-
To locally generate a tarball of everything that will get sent to and published on NPM to really verify and make sure it matches your expectation: npm pack
-
To locally test
- in you package root:
npm link
- in other project:
npm link <yourpackagename>
and in code import <yourpackagename>
- to unlink from the other project:
npm unlink --no-save <yourpackagename>