question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Type definitions are not generated for library mode build

See original GitHub issue

⚠️ IMPORTANT ⚠️ Please check the following list before proceeding. If you ignore this issue template, your issue will be directly closed.

  • Read the docs.
  • Use Vite >=2.0. (1.x is no longer supported)
  • If the issue is related to 1.x -> 2.0 upgrade, read the Migration Guide first.

Describe the bug

Type definitions are not generated for library mode build

Reproduction

  1. Scaffold a react-ts template project.
  2. Run build.
  3. Check the generated assets.

System Info

  • vite version: 2.x
  • Operating System: Mac
  • Node version: 14+
  • Package manager (npm/yarn/pnpm) and version: npm/yarn

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:1
  • Comments:8 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
ghostcommented, Jul 9, 2021

This works perfectly fine in Vite. @yyx990803 mentioned --emitDeclarationOnly flag, but as far as I know, you could get some more advanced options using the @rollup/plugin-typescript plugin which is very well documented.

import { defineConfig } from 'vite'
import path from 'path'
import typescript from '@rollup/plugin-typescript'

const resolvePath = (str: string) => path.resolve(__dirname, str)

export default defineConfig({
  build: {
    lib: {
      entry: resolvePath('../src/index.ts'),
      name: 'index'
    },
    rollupOptions: {
      // make sure to externalize deps that shouldn't be bundled
      // into your library
      external: ['vue'],
      output: {
        // Provide global variables to use in the UMD build
        // for externalized deps
        globals: {
          vue: 'Vue'
        }
      },
      plugins: [
        typescript({
          'target': 'es2020',
          'rootDir': resolvePath('../src'),
          'declaration': true,
          'declarationDir': resolvePath('../dist'),
          exclude: resolvePath('../node_modules/**'),
          allowSyntheticDefaultImports: true
        })
      ]
    }
  }
})

In package.json

  "scripts": {
    "build": "vue-tsc --noEmit && vite build"
  },

Then yarn build

This gives me a dist folder containing:

├── client.es.js
├── client.umd.js
├── context
│   ├── app
│   │   └── index.d.ts
│   ├── components
│   │   └── component.d.ts
│   ├── html
│   │   └── index.d.ts
│   ├── layouts
│   │   └── index.d.ts
│   ├── pages
│   │   └── index.d.ts
│   └── plugins
│       └── index.d.ts
├── engine
│   ├── html
│   │   └── index.d.ts
│   ├── layouts
│   │   └── index.d.ts
│   ├── pages
│   │   └── index.d.ts
│   ├── plugins
│   │   └── index.d.ts
│   ├── router
│   │   └── index.d.ts
│   └── socket
│       └── modules
│           └── pty.d.ts
├── favicon.ico
├── index.d.ts
└── style.css
1reaction
qmhccommented, Apr 16, 2021

Currently I use rollup.js to generate d.ts after vite build.

rollup.config.js

import path from 'path'
import typescript from 'rollup-plugin-typescript2'
import json from '@rollup/plugin-json'
import image from '@rollup/plugin-image'
import { nodeResolve } from '@rollup/plugin-node-resolve'
import vue from 'rollup-plugin-vue' // v5.x for vue2
import styles from 'rollup-plugin-styles'
import { createFilter } from '@rollup/pluginutils'

const filter = createFilter(/\.vue$/)

export default {
  input: path.resolve(__dirname, 'src/index.ts'),
  output: {
    file: path.resolve(__dirname, `dist/${name}.dts.js`),
    format: 'es',
    externalLiveBindings: false
  },
  external: [
    // external modules
  ],
  plugins: [
    // create a simple plugin to resect style for .vue file
    {
      name: 'resect-vue-style',
      transform: async (code, id) => {
        if (!filter(id)) return null

        return {
          code: code.replace(/<style.*>[\s\S]*<\/style.*>/ig, ''),
          map: null
        }
      }
    },
    json({ namedExports: false }),
    image(),
    nodeResolve({ preferBuiltins: true }),
    vue({ needMap: false }),
    styles({
      mode: 'extract',
      onExtract: () => false
    }),
    typescript({
      check: true,
      tsconfig: path.resolve(__dirname, 'tsconfig.json'),
      tsconfigOverride: {
        compilerOptions: {
          sourceMap: false,
          declaration: true,
          declarationMap: true
        },
        exclude: ['**/__tests__']
      }
    })
  ]
}

finished then remove the output file path.resolve(__dirname,`dist/${name}.dts.js`).

I make a script build.js

const fs = require('fs-extra')
const path = require('path')
const execa = require('execa')

main()

async function main() {
  await execa('vite', ['build'], { stdio: 'inherit' })
  await execa('rollup', ['-c'], { stdio: 'inherit' })
  await fs.remove(path.resolve(__dirname,`dist/${name}.dts.js`))
}

package.json

{
  "scripts": {
    "build": "node build.js"
  }
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

How do I add types to a Vite library build? - Stack Overflow
I created the project with the vue-ts preset and in my component I have defined props with their types, and used some interfaces....
Read more >
TypeScript: Adding Custom Type Definitions for Existing ...
Whether or not a library has type definitions is a big factor in deciding whether I'll use it. You can find the type...
Read more >
Build a typescript component library with Vite - Ivancic Josip
To solve the typescript declarations error, we need to generate type declaration files for the components. We will do this using the vue-tsc ......
Read more >
How To Bundle TypeScript Type Definitions - Chris Krycho
Create a custom build that puts the type definitions in the root of your package, instead of putting them alongside the compiled JavaScript ......
Read more >
Documentation - Module Resolution - TypeScript
Finally, if the compiler could not resolve the module, it will log an error. In this case, the error would be something like...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found