【问题标题】:TypeScript declaration for NodeJS modules which exports a class导出类的 NodeJS 模块的 TypeScript 声明
【发布时间】:2020-09-01 02:16:50
【问题描述】:

我正在尝试为HtmlWebpackPlugin 编写 typescript 声明文件,但无法正常工作。

HtmlWebpackPlugin 默认导出是类HtmlWebpackPlugin 的构造函数。我打算这样使用它。

somefile.ts

import * as HtmlWebpackPlugin from 'html-webpack-plugin'
new HtmlWebpackPlugin({..some options...})

我尝试将其定义如下

shim.d.ts

/// <reference path="./shim.d.ts"/>
declare module 'html-webpack-plugin' {
  interface Options {
    title: string,
    filename: string,
    template: string,
    inject: (boolean | 'head' | 'body'),
    favicon: string,
    hash: boolean,
    cache: boolean,
    showErrors: boolean,
    chunks: any,
    chunksSortMode: ('none' | 'auto' | 'dependency'),
    excludeChunks: any,
    xhtml: boolean
  }
  class HtmlWebpackPlugin {
    constructor(options: Options);
  }
  export default ???
}

我想知道在???这里填写什么。我尝试导出HtmlWebpackPlugintypeof HtmlWebpackPlugin,但没有任何效果。它给了我以下类型错误。

【问题讨论】:

    标签: node.js typescript


    【解决方案1】:

    import * as Module from 'module' 表单不再适用于 AMD/CommonJS,以便更好地与 ES6 模块(使用此表单导出整个命名空间)互操作。

    解决方案:

    使HtmlWebpackPlugin默认导出非模块实体。

    declare module 'html-webpack-plugin' {
      interface Options {
        title: string,
        filename: string,
        template: string,
        inject: (boolean | 'head' | 'body'),
        favicon: string,
        hash: boolean,
        cache: boolean,
        showErrors: boolean,
        chunks: any,
        chunksSortMode: ('none' | 'auto' | 'dependency'),
        excludeChunks: any,
        xhtml: boolean
      }
    
      export = class HtmlWebpackPlugin {
        constructor(options: Options);
      }
    }
    

    使用需要的样式导入

    import HtmlWebpackPlugin = require('html-webpack-plugin')
    

    【讨论】:

      【解决方案2】:

      给你,

         export { HtmlWebpackPlugin };
      
         // or you may directly export class
      
         export class HtmlWebpackPlugin {
           constructor(options: Options);
         }
      

      【讨论】:

      • 我认为这行不通。 HtmlWebpackPlugin 是 Node.JS 中的默认导出,所以声明中 HtmlWebpackPlugin 的导出也应该是默认的。
      • 我已经更新了我的问题,以防你想看看
      • 是的,你是对的,这不起作用new HtmlWebpackPlugin({..some options...}),我检查了你是否使用import * as X from "html-webpack-plugin";,然后new X.HtmlWebpackPlugin({..}) 起作用。让我试试看能不能直接用。
      • 我刚刚尝试了export default HtmlWebpackPlugin; 并将其用作“从“html-webpack-plugin”导入 HtmlWebpackPlugin;让 x = new HtmlWebpackPlugin({});'有用。你得到了什么?
      • 可以确认行为是(或曾经是)有意的,无论是使用 babel 还是 typescript,其中 module.exports = Something 出于互操作性原因故意与 export default Something 不同(我认为)。不过,没有给您答案,因为除非您是 HtmlWebpackPlugin 的所有者,否则我不确定如何解决这个问题。更多阅读herehere
      猜你喜欢
      • 2016-12-06
      • 2013-03-08
      • 2021-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多