Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type definitions are not generated for library mode build #2049

Closed
2 of 3 tasks
ayush987goyal opened this issue Feb 17, 2021 · 8 comments
Closed
2 of 3 tasks

Type definitions are not generated for library mode build #2049

ayush987goyal opened this issue Feb 17, 2021 · 8 comments

Comments

@ayush987goyal
Copy link

⚠️ 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
@patak-dev
Copy link
Member

You can add https://github.com/ezolenko/rollup-plugin-typescript2 to your plugins to generate the types (check the docs for options). In your vite.config.js

import typescript2 from "rollup-plugin-typescript2"
          
export default {
  plugins: [
    {
      ...typescript2(),
      apply: 'build',
    },
  ]
}

@ayush987goyal
Copy link
Author

I was wondering why this should need an extra plugin when everything is written in TypeScript and the Vite supports it out of the box. Adding the above mentioned plugin would involve the transpilation twice.

@patak-dev
Copy link
Member

Vite just strips out the types, and let you choose how to use the types (for example, using your IDE or running tsc on the side). Using the typescript compiler in Vite would slow down the processing pipeline

@yyx990803
Copy link
Member

FYI you don't need a plugin... you can also just use tsc with the --emitDeclarationOnly flag.

@odex21
Copy link

odex21 commented Feb 20, 2021

FYI you don't need a plugin... you can also just use tsc with the --emitDeclarationOnly flag.

This does not generate type definitions of the component, but it is possible with the plugin, does it require additional configuration?

@ingro
Copy link

ingro commented Mar 15, 2021

@odex21 I've created good-enough-for-me declarations files by running this command after npm run build, without the need to use typscript2 rollup plugin:

tsc lib/main.ts --declaration --emitDeclarationOnly --jsx react --esModuleInterop --outDir dist

Not sure if there is a better way, but it seems to work for my use case!

@qmhc
Copy link
Contributor

qmhc commented 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"
  }
}

@ghost
Copy link

ghost commented 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

@github-actions github-actions bot locked and limited conversation to collaborators Jul 24, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

6 participants