Hapi.js:“类扩展未定义的值不是构造函数或null”

时间:2018-09-11 19:51:11

标签: typescript api webpack hapijs

我想用Hapi.js和Webpack编译并捆绑整个应用程序,用Typescript编写API。

不幸的是,当我创建最简单的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"
      ]
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

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

假设您打算在Node上运行捆绑软件,则需要向Webpack配置中添加target: 'node',以告知Webpack允许生成的捆绑软件使用Node内置模块而无需重定向。参见the documentation