【问题标题】:Webpack compilation hash in client code客户端代码中的 Webpack 编译哈希
【发布时间】:2018-07-31 08:04:56
【问题描述】:

问题

我正在尝试将编译哈希作为 Angular 客户端代码中的变量。我最初的想法是通过 DefinePlugin 使用 ExtendedAPIPlugin 插件。 Webpack 插件文档声明

ExtendedAPIPlugin -> 将有用的免费变量添加到包中。

__webpack_hash__ 编译的哈希值作为免费变量提供。

webpack.config.js

    plugins: [
        new webpack.ExtendedAPIPlugin(),
        ...
        new webpack.DefinePlugin({
            'process.env': {
                'NODE_ENV': JSON.stringify(env),
                'DEP_HASH': JSON.stringify(__webpack_hash__) // ???
            }
        })
      ]

客户端代码

process.env.DEP_HASH

然而,webpack 构建抱怨:

ReferenceError: __webpack_hash__ is not defined

那么这个__webpack_hash__变量可以在哪里以及如何使用呢?

Webpack 版本:3.10.0

解决方案

declare var __webpack_hash__: any;

export class SomeClass {
   ...
   private someFunction(): void {
      let hash = __webpack_hash__(); // Not AOT
      let hash = __webpack_hash__;   // AOT 
   } 
   ...
}

【问题讨论】:

    标签: angular webpack


    【解决方案1】:

    直接在您的应用程序代码中使用它:

    view.js

    class SomeView { constructor() { this.hash = __webpack_hash__; } }

    如果您使用的是 Typescript,则需要将 __webpack_hash__ 定义为全局变量。我想这会做到:

    declare var __webpack_hash__: string;

    【讨论】:

    • 恐怕编译不出来TS2304: Cannot find name '__webpack_hash__'.
    • 这么简单!谢谢!只需将类型声明为函数:declare var __webpack_hash__: Function;
    猜你喜欢
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 2015-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多