【问题标题】:Nodejs/Express/Typescript require the module.exportsNodejs/Express/Typescript 需要 module.exports
【发布时间】:2020-08-31 08:44:32
【问题描述】:

我正在尝试使用 Express 创建一个 Web 服务,它可以从 localhost 以及使用 Claudia 的 AWS Lambda 执行。

我想将应用配置和 app.listen 函数分开。

我的 app.ts 文件如下所示:

import express = require('express');
const dotenv = require('dotenv');

class App {

  public app: express.Application = express();

  constructor() {
    dotenv.config();

    // parse application/json request body to JSON Objects
    this.app.use(express.json());

    // parse x-ww-form-urlencoded request body to JSON Objects
    this.app.use(express.urlencoded({ extended: true }));

    this.app.get('/', (req, res) => {
      res.send('API server is up and running');
    });
  }
}

module.exports = new App().app

然后,我需要 local.ts 文件中的应用程序

const app = require('./app');

app.listen(process.env.PORT,
    () => console.log(`Application is running on port ${process.env.PORT}`)
);

我的 package.json 看起来像这样

{
  "name": "nodejs-express-lambda",
  "version": "1.0.0",
  "description": "",
  "main": "app.ts",
  "scripts": {
    "run": "npx ts-node local.ts",
    "build": "tsc"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/dotenv": "^8.2.0",
    "dotenv": "^8.2.0",
    "express": "^4.17.1"
  },
  "devDependencies": {
    "@types/express": "^4.17.6",
    "@types/node": "^14.0.1",
    "claudia": "^5.12.0",
    "ts-node": "^8.10.1",
    "tslint": "^6.1.2",
    "typescript": "^3.9.2"
  }
}

tsconfig.json

{
  "compilerOptions": {
      "module": "commonjs",
      "target": "ES6"
  },
  "exclude": [
      "node_modules",
  ]
}

最后,运行npm run-script run 将返回

app.listen 不是函数

应用程序正在端口 3000 上运行

我试过import app = require('./app'),但也没有用。我对所有这些出口和进口有点迷茫,有人可以帮忙吗?

app.ts 运行 app.listen 效果很好。

【问题讨论】:

    标签: node.js typescript express import require


    【解决方案1】:

    我不确定这是否会有所帮助,但您可能想试试这个:

    import express from 'express'
    import dotenv from 'dotenv' // or just import 'dotenv/config'
    
    class App {
    
      public app: express.Application = express();
    
      constructor() {
        dotenv.config();
    
        // parse application/json request body to JSON Objects
        this.app.use(express.json());
    
        // parse x-ww-form-urlencoded request body to JSON Objects
        this.app.use(express.urlencoded({ extended: true }));
    
        this.app.get('/', (req, res) => {
          res.send('API server is up and running');
        });
      }
    }
    
    const app = new App().app
    export default app
    

    在第二个文件中

    import app from './app'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-01
      • 1970-01-01
      • 2020-04-06
      • 2019-01-02
      • 1970-01-01
      相关资源
      最近更新 更多