【问题标题】:What is the type of the webpack config function when it comes to TypeScript?当涉及到 TypeScript 时,webpack 配置函数的类型是什么?
【发布时间】:2022-05-09 00:50:59
【问题描述】:

使用 TypeScript 编写配置时,我无法确定 webpack 配置函数的类型。

目前我导出了一个类型为Configuration的对象:

const config: Configuration = {
  mode: 'production',
  // ...
}
export default config;

应该改为导出函数:

export default (...): ... => {
  return {
    mode: 'production'
    // ...
  }
}

但我不知道该函数的正确类型,也无法在类型定义中找到它:

https://github.com/webpack/webpack/blob/main/types.d.ts

有什么想法吗?

【问题讨论】:

    标签: typescript webpack


    【解决方案1】:

    目前似乎没有成熟或推荐的解决方案。

    与此同时,我所做的是这个。

    webpack.types.ts:

    import type { Configuration } from "webpack";
    import type { Configuration as DevServerConfiguration } from "webpack-dev-server";
    
    export interface WebpackConfiguration extends Configuration {
      devServer?: DevServerConfiguration;
    }
    
    type CLIValues = boolean | string;
    
    type EnvValues = Record<string, CLIValues | Record<string, Env>>;
    
    interface Env extends EnvValues {}
    
    type Argv = Record<string, CLIValues>;
    
    export interface WebpackConfigurationGenerator {
      (env?: Env, argv?: Argv): Configuration | Promise<Configuration>;
    }
    

    webpack.config.ts

    import type { WebpackConfigurationGenerator } from "./webpack.types";
    
    const generateConfig: WebpackConfigurationGenerator = (env, argv) => {
      // ...
    };
    
    export default generateConfig;
    

    【讨论】:

    • 但是我不太确定,必须修补配置类型以添加​​ webpack-dev-server 类型 - 我相信它是自动完成的(至少对我来说它以某种方式工作,因为我已经安装@types/webpack-dev-server 包)。但其余的很清楚,您实现了缺少的类型:) 谢谢!我刚刚在他们的问题队列中问了这个问题:github.com/webpack/webpack/issues/14508:也许我们错过了什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-01
    • 2021-05-13
    • 1970-01-01
    • 2016-11-22
    • 2012-04-17
    相关资源
    最近更新 更多