I've been using TypeScript in my projects for the past month or so. After a two year hiatus, it finally seems right for me. Using it in an app is documented everywhere, but adding it into a package for NPM seems more scattered. Here's a real easy way to set this up with Babel 7.

Install TypeScript

npm install typescript --save-dev

Next, let's install the needed Babel 7 dependencies:

npm install @babel/cli @babel/core @babel/preset-typescript --save-dev

If you are building something with React, you will want to have @babel/preset-react and @types/react saved as devDependencies as well.

Add Build Scripts

Next lets add a couple build scripts to our package.json:

"build": "npx babel src --out-dir lib --extensions \".ts,.tsx\"",
"export-types": "tsc --emitDeclarationOnly",
"check-types: "tsc"

Add Two Configuration Files

Let's create our .babelrc file:

  "presets": ["@babel/preset-react", "@babel/typescript"]

If you aren't using React, leave that one out.

We're almost done, now let's create our tsconfig.json

  "compilerOptions": {
    "target": "esnext",
    "baseUrl": "src",
    "sourceMap": true,
    "lib": ["dom", "dom.iterable", "esnext"],
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "downlevelIteration": true,
    "jsx": "preserve",
    "declaration": true,
    "outDir": "lib"
  "include": ["src"]

You can view the reference guide that explains how this file works, or use it as is. One thing to make note of, is the outDir needs to be the same as the --out-dir flag in our babel command above. This ensures our types get put into the correct place, next to the js that babel compiles.

That's it

With the configuration files in place, our build scripts added, and packages installed, you're all set!

Before publishing to npm, run npm run build && npm run export-types. You will now offer plain JS for anyone and type definitions for those using TypeScript :)

This is being used on my new react-use-upload hook for React and can be referenced there for more info.