我可以导入 node-postgres 模块 (pg) 还是只导入 CommonJS?

Sup*_*ame 6 javascript node.js node-postgres es6-modules

我一直在使用老式 JavaScriptconst var = require('var').编写我的大部分 API,现在我正在使用ES6 语法编写我的第一个 API,包括使用 import 而不是 require。我总是使用 node-postgres 模块,const {Pool} = require('pg')但是当我尝试编写它时import {Pool} from 'pg'出现错误

SyntaxError: The requested module 'pg' does not provide an export named 'Pool'.

同样,import Pool from 'pg'给我

TypeError: Pool is not a constructor

有没有办法将它作为 ES6 模块导入,或者我是否需要为我的 ES6 postgres 连接找到另一个包?我在网上找不到任何使用 node-postgres 和导入的人的例子。

Pri*_*ega 9

这应该处理我认为的。

import * as pg from 'pg'
const { Pool } = pg
Run Code Online (Sandbox Code Playgroud)

  • `const { 池 } = pg.default` (10认同)
  • 如果您使用 import pg from 'pg'` 而不是 import * as pg from 'pg'`,则可以使用 `const { Pool } = pg` 而不是 `const { Pool } = pg.default` (5认同)
  • 这会给出错误“类型‘typeof import("/home/server/pg")’上不存在属性‘池’”。const { Pool } = pg`,即使使用allowSyntheticDefaultImports。 (2认同)