【问题标题】:Webpack fails with Node FFI and Typescript - dynamic require errorWebpack 因 Node FFI 和 Typescript 失败 - 动态需要错误
【发布时间】:2017-03-15 22:53:27
【问题描述】:

在一个简单的 Typescript 程序中,我使用 require 节点 FFI

import  * as Electron   from  'electron';`
import  * as ffi        from  'ffi';`

然后

mylib = ffi.Library('libmoi', {
  'worker': [ 'string', [ 'string' ]  ],
  'test'  : [ 'string', []            ]
  } );

通过 webpack 将其链接起来

WARNING in ./~/bindings/bindings.js
Critical dependencies:
76:22-40 the request of a dependency is an expression
76:43-53 the request of a dependency is an expression
 @ ./~/bindings/bindings.js 76:22-40 76:43-53

问题似乎是 FFI 有一个动态的require,而修复似乎是在webpack.config.js 文件中应用webpack.ContextReplacementPlugin

这有点超出我的能力范围,但 Angular 案例的示例是:

plugins: [
      new webpack.ContextReplacementPlugin(
        // The (\\|\/) piece accounts for path separators in *nix and Windows
        /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
        root('./src') // location of your src
      )
  ]

知道如何为 FFI 执行此操作吗?

【问题讨论】:

  • 你发现了吗?
  • 是的,答案如下。

标签: node.js typescript webpack electron node-ffi


【解决方案1】:

我也有类似的问题,不知何故,我设法解决了。我先解释一下我的理解。

webpack 的主要工作是将单独的代码文件捆绑到一个文件中,默认情况下它会捆绑其树中引用的所有代码。

一般有两种node_modules:

  1. 用于浏览器端(角度、rxjs 等)
  2. 用于 nodejs 端(express、ffi 等)

捆绑浏览器端node_module更安全,但捆绑节点端node_module并不安全,因为它们不是这样设计的所以解决方案分为以下两个步骤:

  1. 在 webpack.config.js 文件中提供适当的目标(节点、电子等),例如 "target":'electron-renderer' 默认是浏览器
  2. 在 webpack.config.js 文件中将 node_side 模块声明为外部依赖,例如

    "externals": {
        "bindings": "require('bindings')",
        "ffi": "require('ffi')"
    }
    

【讨论】:

    【解决方案2】:

    这里是答案:github issue comment on the Johnny-Five repo

    引用 brodo 的回答,这就是你要阻止 webpack 被“绑定”和类似的东西缠住的方法:

    ... the webpack config looks like this:
    
    module.exports = {
      plugins: [
        new webpack.ContextReplacementPlugin(/bindings$/, /^$/)
      ],
      externals: ["bindings"]
    }
    

    【讨论】:

    • 当我这样做时出现以下错误ReferenceError: bindings is not defined
    • Webpack 已更改。您需要更新答案以适应新版本。
    猜你喜欢
    • 2021-02-11
    • 2014-07-19
    • 2018-05-03
    • 2020-10-07
    • 1970-01-01
    • 2021-06-13
    • 1970-01-01
    • 2017-05-09
    • 1970-01-01
    相关资源
    最近更新 更多