是否可以在TypeScript中编写webpack配置?

我在搜索时看到有webpack的类型。看来我可以用TypeScript写webpack.config.js吗?但是我该怎么办呢?

在此处输入图片说明

SamPro2020/03/24 14:23:53

我写了一篇博客文章“使用TypeScript编写Webpack配置”以获取全部详细信息,这是TLDR:

接受的答案对我不起作用,我还发现该ts-node依赖项不支持ES6导入语句。

我发现的最简单的方法是简单地运行TypeScript tsc工具将TypeScript转换为JavaScript,然后webpack照常运行该工具:

tsc --lib es6 webpack.config.ts
webpack --config webpack.config.js

与其他答案一样,这具有不需要安装任何依赖项的附加优点。

奖金最高提示

Webpack类型是Webpack 1和2语法的混合。您可以使用TypeScript来确保仅使用Webpack 2语法,并从Webpack 1语法中删除所有类型。我通过创建一些扩展Webpack类型的新类型来做到这一点:

// webpack.common.ts
import * as webpack from "webpack";

export type INewLoader = string | webpack.NewLoader;
export interface INewUseRule extends webpack.NewUseRule {
  use: INewLoader[];
}
export interface INewLoaderRule extends webpack.NewLoaderRule {
  loader: INewLoader;
}
export type INewRule = INewLoaderRule | INewUseRule |
    webpack.RulesRule | webpack.OneOfRule;
export interface INewModule extends webpack.NewModule {
  rules: INewRule[];
}
export interface INewConfiguration extends webpack.Configuration {
  module?: INewModule;
}
export interface IArguments {
  prod: boolean;
}
export type INewConfigurationBuilder = (env: IArguments) => INewConfiguration;

然后,您可以在Webpack配置中使用以下类型:

import * as path from "path";
import * as webpack from "webpack";
import { INewConfiguration, INewConfigurationBuilder } from "./webpack.common";

const configuration: INewConfiguration = {
  // ...
};
export default configuration;

或者您可以像这样将参数传递到您的webpack配置文件:

import * as path from "path";
import * as webpack from "webpack";
import { IArguments, INewConfiguration, INewConfigurationBuilder } from "./webpack.common";

const configurationBuilder: INewConfigurationBuilder = 
  (env: IArguments): INewConfiguration => {
    const isDevBuild = !(env && env.prod);
    const configuration: INewConfiguration = {
      // ...
    };
    return configuration;
  };
export default configurationBuilder;

您可以像这样将参数传递给webpack:

webpack --env.prod

番长2020/03/24 14:23:53

我在webpack源代码中找不到任何线索,您可以将webpack.config.ts文件直接用作项目的配置。

当然,由于TypeScript只是Javascript的超集,因此您始终可以使用TypeScript编写您的脚本webpack.config.ts并将其转换为有效的Javascript webpack.config.js文件。