node-postgres ('pg'.Client) 的 webpack 导入错误

Ren*_*rop 7 postgresql node.js node-postgres webpack babeljs

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

./~/pg/lib/native/index.js 模块中的错误未找到:错误:无法解析 .../node_modules/pg/lib/native @ ./~/pg/lib/ 中的模块“pg-native”本机/index.js 9:13-33

ignore.babelrc 中尝试了几个语句,但没有让它运行......

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

const Client = require('pg').Client;

console.log("done");
Run Code Online (Sandbox Code Playgroud)

webpack.config.js

module.exports = {
  entry: './handler.js',
  target: 'node',
  module: {
    loaders: [{
      test: /\.js$/,
      loaders: ['babel'],
      include: __dirname,
      exclude: /node_modules/,
    }]
  }
};
Run Code Online (Sandbox Code Playgroud)

.babelrc

{
  "plugins": ["transform-runtime"],
  "presets": ["es2015", "stage-1"]
}
Run Code Online (Sandbox Code Playgroud)

包.json

"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"
}
Run Code Online (Sandbox Code Playgroud)

有点相关的 github 问题:

Ale*_*man 10

这确实是一个旧线程,但仍然对我有帮助。Steve Schafer 1提供的解决方案很好,但不是最简单的。

相反,Marco Lüthy 2在链接问题中提供的可能是最容易设置的,因为它是纯配置,甚至不需要创建虚拟文件。

它包括修改您的 Webpack 配置plugins数组,如下所示:

const webpack = require('webpack');

const webpackConfig = {
  ...
  resolve: { ... },
  plugins: [
    new webpack.IgnorePlugin(/^pg-native$/)
    // Or, for WebPack 4+:
    new webpack.IgnorePlugin({ resourceRegExp: /^pg-native$/ })
  ],
  output: { ... },
  ...
}
Run Code Online (Sandbox Code Playgroud)

更新以包含评论中建议的更改。

  • 谢谢,它成功了。对于 webpack 4+,语法略有不同 `new webpack.IgnorePlugin({ resourceRegExp: /^pg-native$/ }),` (5认同)

Ste*_*fer 7

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

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

{
  ...
  resolve: {
    alias: {
      ...
      'pg-native': path-to-dummy-js-file,
      'dns': path-to-dummy-js-file
    }
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)

其中虚拟文件包含一行:

export default null
Run Code Online (Sandbox Code Playgroud)

请参阅https://github.com/brianc/node-postgres/issues/838以获取进一步的讨论和替代解决方法。


Pet*_*nik -1

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