【问题标题】:Convert pg (postgress node module) native from require to import将 pg(postgress 节点模块)本机从 require 转换为 import
【发布时间】:2016-08-20 10:44:21
【问题描述】:

我使用转译器将 es6 / typescript 代码转换为 es5。 这是原始的 es5 代码,带有用于 node js 的 pg 本机模块导入:

var pg  = require('pg').native

我使用 es6/typsecript 模式:

import * as pge from "pg"

效果很好,但我找不到指定 .native 的语法,因此它被正确转换为 require('pg').native

我试过了:

import * as pge from "pg"
export let pg       = pge.native

但我不确定这是否是正确的方法。有没有更好的办法?

【问题讨论】:

    标签: node.js postgresql import ecmascript-6


    【解决方案1】:

    这就是我最终使用的方式,并且工作正常。

    import PG from 'pg';
    
    const Pool = PG.Pool;
    
    export const connection  =  new Pool({
        user: 'xxxxx',
        host: 'xxxxx',
        database: 'xxxxx',
        password: 'xxxxx',
        port: xxxx,
      });
    

    【讨论】:

      【解决方案2】:

      正确的语法是:

      import { native as pg } from 'pg';
      

      等同于:

      var pg = require('pg').native;
      

      然后,您将照常使用 pg 变量。

      【讨论】:

      • 似乎可以工作,但 tslint 说“pg 没有本地导出成员”.. 我想这是定义的问题,并不能阻止它工作,你知道我怎么能摆脱这个错误?
      • 你需要包定义,幸运的是这些存在于DefinitelyTyped
      • 刚刚出泄漏问题。如何关闭pg连接?我试过 pg.end() 但它不起作用。这是我最初的问题stackoverflow.com/q/48617031/2547005
      猜你喜欢
      • 2018-08-13
      • 2018-10-26
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      • 2019-10-09
      • 2022-01-17
      • 2022-11-17
      • 1970-01-01
      相关资源
      最近更新 更多