关于node.js:webpack的node-postgres(‘pg’.Client)导入错误

webpack import error with node-postgres ('pg'.Client)

尝试将以下文件与Webpack捆绑在一起失败

ERROR in ./~/pg/lib/native/index.js Module not found: Error: Cannot
resolve module 'pg-native' in
.../node_modules/pg/lib/native
@ ./~/pg/lib/native/index.js 9:13-33

我在.babelrc中尝试了几个ignore语句,但没有使其运行...

我想捆绑的测试文件:handler.js

1
2
3
const Client = require('pg').Client;

console.log("done");

webpack.config.js

1
2
3
4
5
6
7
8
9
10
11
12
module.exports = {
  entry: './handler.js',
  target: 'node',
  module: {
    loaders: [{
      test: /\\.js$/,
      loaders: ['babel'],
      include: __dirname,
      exclude: /node_modules/,
    }]
  }
};

.babelrc

1
2
3
4
{
 "plugins": ["transform-runtime"],
 "presets": ["es2015","stage-1"]
}

package.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
"dependencies": {
 "postgraphql":"^2.4.0",
 "babel-runtime":"6.11.6"
},
"devDependencies": {
 "babel-core":"^6.13.2",
 "babel-loader":"^6.2.4",
 "babel-plugin-transform-runtime":"^6.12.0",
 "babel-preset-es2015":"^6.13.2",
 "babel-preset-stage-0":"^6.5.0",
 "babel-polyfill":"6.13.0",
 "serverless-webpack":"^1.0.0-rc.3",
 "webpack":"^1.13.1"
}

一些相关的github问题:

  • https://github.com/brianc/node-postgres/issues/1187
  • https://github.com/serverless/serverless-runtime-babel/issues/8


这是一个旧线程,但问题仍然存在,因此对于任何遇到此问题的人,都有解决方法。问题在于node-postgres的编写方式与babel的代码重写方式之间存在相互作用,即使没有显式导入/要求,也会强制加载pg-native

最简单的解决方法是在您的webpack.config.js中添加几个别名,以使其链接到虚拟空文件中:

1
2
3
4
5
6
7
8
9
10
11
{
  ...
  resolve: {
    alias: {
      ...
      'pg-native': path-to-dummy-js-file,
      'dns': path-to-dummy-js-file
    }
  }
  ...
}

虚拟文件包含一行:

1
export DEFAULT NULL

请参阅https://github.com/brianc/node-postgres/issues/838了解更多讨论和替代解决方法。


您可能在本地全局安装了pg-native。因此,数据包管理器在锁定文件中不包含pg-native。这是我在本地运行良好时遇到的一个问题,但是每次我在云Webpack中构建时,都会抱怨缺少pg-native。我通过删除推送到云中的文件中的锁文件(在本例中为seed.run)解决了该问题。


您必须安装pg-native

1
npm install pg-native