【问题标题】:Hapi.js: "Class extends value undefined is not a constructor or null"Hapi.js:“类扩展值未定义不是构造函数或空值”
【发布时间】:2019-02-16 09:24:30
【问题描述】:

我想在 Typescript 中编写一个 API,使用 Hapi.js 和 webpack 转译和捆绑整个应用程序。

不幸的是,当我创建最简单的 Hapi 服务器(甚至创建服务器实例)时,我收到以下错误:

exports = module.exports = internals.Response = class extends Http.ServerResponse {
                                                                   ^

TypeError: Class extends value undefined is not a constructor or null

```

我的 Hapi 版本是 ^17.5.4 和类型 ^17.0.19,两者都应该是最新版本。

index.ts

import {Server, ServerOptions} from 'hapi';

const options: ServerOptions = {
    host: 'localhost',
    port: '9000'
}

const server = new Server(options); // instsantiating the server causes the error

webpack.config.ts

const path = require('path');

module.exports = {
    entry: './app/index.ts',
    mode: 'development',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'app.bundle.js',
    },
    resolve: {
        extensions: ['.ts', '.js'],
        modules: [
             "node_modules",
             path.resolve(__dirname, "app")
        ],
    },
    module: {
         rules: [
            { test: /\.ts$/, loader: 'ts-loader' }
         ]
    },
    devtool: 'inline-source-map',
    node: {
        fs: 'empty',
        net: 'empty'
    }
};

tsconfig.json

{
    "compilerOptions": {
        "module": "esnext",
        "target": "es5",
        "noImplicitAny": true,
        "removeComments": true,
        "sourceMap": true,
        "watch": true,
        "forceConsistentCasingInFileNames": true,
        "noImplicitThis": true,
        "lib": ["ES2015", "dom"],
        "moduleResolution": "node"
    },
    "compileOnSave": true,
    "include": [
        "*/src/**/*.ts",
        "*/src/**/*.tsx",
        "*/tests/**/*.ts",
        "*/index.ts",
        "tsd.d.ts"
      ]
}

感谢任何帮助!

【问题讨论】:

    标签: typescript api webpack hapijs


    【解决方案1】:

    Hapi.js 间接引用了 Node 的内置 http 模块,并且默认情况下,Webpack 将对 Node 内置模块的引用重定向到其与浏览器兼容的替换模块,这可能无法提供节点内置模块。在这种情况下,http 的替换没有 ServerResponse 导出,因此会出现运行时错误。 (不幸的是,这在构建时没有被捕获,我认为是因为 ts-loader 不够聪明,无法将 TypeScript 重定向到浏览器兼容模块的类型。)

    假设你打算在 Node 上运行你的包,你需要将 target: 'node' 添加到 Webpack 配置中,以告诉 Webpack 允许生成的包使用 Node 内置模块而无需重定向。见the documentation

    【讨论】:

    • 有道理,感谢您的精彩解释和文档链接,马特!对配置的微小改动,产生了很大的影响;)
    • 你找到解决办法了吗?我正面临这个问题
    猜你喜欢
    • 1970-01-01
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 2022-01-22
    • 2021-05-23
    • 2021-04-15
    • 2012-03-27
    相关资源
    最近更新 更多