vue-cli: Can not emit declaration files for TypeScript

Version

3.0.0-beta.6

Reproduction link

https://github.com/HuijiFE/void-ui/tree/0.1

Steps to reproduce

git clone git@github.com:HuijiFE/void-ui.git
cd void-ui
git checkout 0.1
yarn
yarn build:void

What is expected?

Output declaration files after building.

What is actually happening?

There is not any declaration files after building.


I have set "declaration": true, in tsconfig.json, but it doesn’t output the typescript declaration files.

And then I use tsc --emitDeclarationOnly, although it output the declaration files but without vue single file component.

About this issue

  • Original URL
  • State: open
  • Created 6 years ago
  • Reactions: 27
  • Comments: 54 (8 by maintainers)

Commits related to this issue

Most upvoted comments

I just hit this issue myself. The solution for me was substantially similar to some of the previous ones claimed to work, but with some key differences. This is my vue.config.js:

module.exports = {
  chainWebpack: config => {
    // These are some necessary steps changing the default webpack config of the Vue CLI
    // that need to be changed in order for Typescript based components to generate their
    // declaration (.d.ts) files.
    //
    // Discussed here https://github.com/vuejs/vue-cli/issues/1081
    if(process.env.NODE_ENV === 'production') {
      config.module.rule("ts").uses.delete("cache-loader");

      config.module
        .rule('ts')
        .use('ts-loader')
        .loader('ts-loader')
        .tap(opts => {
          opts.transpileOnly = false;
          opts.happyPackMode = false;
          return opts;
        });
    }
  },
  parallel: false,
}

In particular, the section in previous examples that disabled thread-loader had no effect. I had to add parallel: false to avoid the error Cannot read property 'options' of undefined.

Additionally (this is obvious but bears mentioning), you must specify "declaration": true in your tsconfig.json to have declaration files emitted. This is with the latest (4.1.x) Vue CLI.

Same here for library 😦 npx vue-cli-service build --target lib --dest lib ./src/index.ts

I have set “declaration”: true, in tsconfig.json, but it doesn’t output the typescript declaration files.

I’m using @vue/cli 4.5.6 , none of you guys solution works for me… how sad…

Oh my… It’s been 2 years past, the year of Vue3, the year of TypeScript. now, I can’t believe this bug is still there 😱

@Joehunk’s answer works for me. I’ve added it in an object so I can remove it more easily when this issue is solved.

/**
 * These are some necessary steps changing the default webpack config of the Vue CLI
 * that need to be changed in order for TypeScript based components to generate their
 * declaration (.d.ts) files.
 * Discussed here https://github.com/vuejs/vue-cli/issues/1081
 */
const fixEmitDeclarationFilesForTypeScript = {
  chainWebpack: (config) => {
    if (process.env.NODE_ENV === 'production') {
      config.module.rule('ts').uses.delete('cache-loader');
      config.module
        .rule('ts')
        .use('ts-loader')
        .loader('ts-loader')
        .tap((options) => ({
          ...options,
          transpileOnly: false,
          happyPackMode: false,
        }));
    }
  },
  parallel: false,
};

module.exports = {
  ...fixEmitDeclarationFilesForTypeScript,
  // some other configuration
};

However, it is indeed possible to generate the declaration files after the build of your application. All you have to do is run the tsc --emitDeclarationOnly command after the build. That’s probably the fastest way. EDIT NOTE: this way do not generate declaraction files for .vue files.

{
  "scripts": {
    "build": "vue-cli-service build --target lib --name library src/index.ts && tsc --emitDeclarationOnly"
  }
}

This doesn’t seem to be a Vue issue… At least doesn’t qualify as a bug report.

This should be automatically built into vue-cli build command when you pass in .ts file as root and have declaration: true in the tsonfig.json of your project.

Why would I ever want to export a library build of vue component without types? It guarantees compiler warnings on the client side who uses the library.

struggled for a while with the problem, @XavierChevalier’s solution works. But make sure also update the tsconfig.json to specify the *.d.ts directory (declarationDir), also update the package.json to set typings to specify main declariation file. For example: tsconfig.json

    "declaration": true,
    "declarationDir": "dist",

package.json

  "typings": "./dist/src/index.d.ts",

Same issue. Very unsatisfying to have this still open.

Any update on this?

@m-thomson Yes, I finally turned to using rollup.js from scratch… which is the approach of vue 3 repo. You might want to do so as well, I don’t think this will be fixed, because this issue exists from 2018.

Any progress on this?

@eakarpov Hello, here’s my current configuration file with which I get the precious .d.ts files !

// vue.config.js

module.exports = {
  configureWebpack: config => {
    if(process.env.NODE_ENV === 'production') {
      config.module.rules.forEach(rule => {
        if (rule.use) {
          let idx = rule.use.findIndex(w => w.loader === 'thread-loader')
          if (idx !== -1) rule.use.splice(idx, 1)
        }
      })
    }
  },
  chainWebpack: config => {
    if(process.env.NODE_ENV === 'production') {
      // disable cache (not sure if this is actually useful...)
      config.module.rule("ts").uses.delete("cache-loader");

      config.module
        .rule('ts')
        .use('ts-loader')
        .loader('ts-loader')
        .tap(opts => {
          opts.transpileOnly = false;
          opts.happyPackMode = false;
          return opts;
        });
    }
  }
}

The only small problem is that it emits empty declarations files for the tests (*.spec.ts, if someone has an idea how to ignore them I am interested) but everything else works well 😃

I just ended up removing vue-cli and using webpack directly 😦 it was becoming too much of a time sink and faff to build TS related libraries with vue-cli.

If you are going to be doing re-usable ts based components or libraries then I would suggest just skipping vue cli and just building it all yourself with webpack, as its been almost a year now and the workarounds are not great. If you are however just making an “application” for running then vue cli is great (but I would question why you would need declaration files in that scenario).

If it helps anyone, here is an example webpack used to basically do the same stuff vue cli was doing for me (bundling ts, sass, vue files etc).

https://github.com/alchemist/alchemist-core/blob/master/webpack.config.js

Declaration files are only relevant when generating a library consumable by a package manager. The build time overhead would only happen in this case. We could disable HappyPack in this case only.

I will cook up a quick PR.

yes, ts-loader related issue. I’m wondering if we need to change the build task for projects with the typescript plugin to change the related options so that we still see the performance gains during development (serve), but build the definitions file during a full build. You could modify your webpack config in your vue.config.js to fix the issue locally by adding

config.module
  .rule('ts')
    .use('ts-loader')
      .loader('ts-loader')
        .tap(opts => {
          opts.transpileOnly = false;
          opts.happyPackMode = false;
          return opts;
        });

to disable the transpileOnly and happyPackMode options.

EDIT NOTE: this way do not generate declaraction files for .vue files.

That’s kind of the point though haha… any progress? Anybody?

after some further investigation, it seems that (at least in my case), the issue is related with the ‘thread-loader’ package that the ‘cli-plugin-typescript’ is using… if I set parallel: false in the vue.config.js, the typings are correctly emitted, if I override the ‘ts-loader’-options as @dhensche suggested!

@dhensche I’ve tried your suggestion with vu-cli 3.0. When opts.happyPackMode = false I get the following error during build:

error in ./src/index.ts


Module build failed (from ./node_modules/thread-loader/dist/cjs.js):
Thread Loader (Worker 0)
Cannot read property 'options' of undefined

    at Object.makeServicesHost (C:\...\node_modules\ts-loader\dist\servicesHost.js:18:66)
    at successfulTypeScriptInstance (C:\...\node_modules\ts-loader\dist\instances.js:164:45)
    at Object.getTypeScriptInstance (C:\...\node_modules\ts-loader\dist\instances.js:51:12)
    at Object.loader (C:\...\node_modules\ts-loader\dist\index.js:16:41)

 @ ./node_modules/@vue/cli-service/lib/commands/build/entry-lib.js 2:0-24 3:15-18 4:0-22 4:0-22

|  Building for production as library (commonjs + umd)...

(Oddly enough, if I comment out opts.happyPackMode = false; everything is fine).

With VueJS 3 you can use vue-tsc --declaration --emitDeclarationOnly when you add the package vue-tsc

https://github.com/johnsoncodehk/volar/tree/master/packages/vue-tsc

This will generate the declaration file where you have set your outDir in tsconfig.json

@khuguet-tfg you need to delete cache-loader:

chainWebpack: config => {
    config.module.rule("ts").uses.delete("cache-loader");
    config.module.rule("tsx").uses.delete("cache-loader");
}

For some reason the workaround (stopping parallel, removing the happy stuff, add declaration config to tsconfig) behaviour has changed slightly in the new versions. It still outputs the d.ts files but where I used to have to use:

"declarationDir": "." // change from "." to "dist"

This will then go back to putting the d.ts files in the dist folder, for some reason it used to always work relative to the dist folder so "." would indicate to bung the files there, but now it seems to work relative to the root directory for the declaration files.

Not a clue as to why and I dont have the time to go and investigate further but incase anyone has the same issue just change the declaration directory in your tsconfig. I would still ideally want a proper solution to this problem as some of my projects are taking 30 seconds+ to build the library with the workaround in place 😦

@Robula Here you go https://github.com/yaquawa/muku-ui/blob/master/rollup.config.js What you want is the rollup-plugin-dts plugin.

Ok, the transpileOnly: false and happyPackMode: false does indeed give me *.vue.d.ts files but they do not seem very useful. If I obtain a reference (ref=“myComp”) to a published component in an application using the library, I do not get code completion nor does it satisfy eslint; regardless of whether I am referencing props, methods or setup() results. Even using such a reference inside another component in the same library does not work. What am I missing? PS: components are in .vue files (Vue 2.x.x) and defined with the @vue/composition-api using defineComponent(…

For production mode I had to specify declarations via the ts-loader compiler options:

config.module.rules.forEach( r => {
      if (r.use)
        r.use.forEach( u => {
          if (u.loader.match(/ts-loader/)) {
            u.options.transpileOnly = false
            u.options.configFile = 'tsconfig.webpack.json'
            u.options.logLevel = 'info'
            u.options.compilerOptions = {
              "declaration": true
            }
          }
        })
    })

Might have something to do with the NODE_ENV getting set to production and some ts-loader internal config… Unsure, but it resolved for me.

EDIT: Apparently this has not resolved it. It only randomly(about 50% of the time) emits…

EDIT2: I removed the cache loader rule for vue as well, config.module.rule('vue').uses.delete('cache-loader'), and have successfully built my project about 10 times in a row with the d.ts files emitted.

I tried set happyPackMode to false in chainWebpack config item, and also set parallel to false, but when I try building the vue app I get stuck, after 10 minutes, I get error JavaScript heap out of memory.

My Node version: 12.16.3, vue cli version 4.3.1

I found that my hang issue is caused by composition api library, issue link is https://github.com/vuejs/composition-api/issues/330, use command tsc -d to compile ts code can directly generate d.ts file.

All these things did not work for me. I switched to rollup. I someone is interested here is my TS+vuetify+rollup SFC starter template: https://github.com/MikeMitterer/vue-ts-sfc-starter

@eakarpov This seems to be related to thread-loader,

The workaround proposed in this issue is to simply disable thread-loader.

Because this will slow down the build, you can disable it only for production builds when you want to emit the declaration files.

Please let me know if you find a better solution 😃

I’m dealing with this issue as well, and when applying the suggested workaround the type definition files are properly generated, but only on the initial build, any additional builds will clear out the dist folder and after it is rebuilt the type files are not regenerated.