【问题标题】:How do you make node modules available in the Purescript REPL?如何在 Purescript REPL 中提供节点模块?
【发布时间】:2019-06-30 20:28:55
【问题描述】:

通过pulp repl运行时是否可以使所有节点模块可用?似乎有些仅在通过pulp run 调用时才有效。

我正在遵循 Purescript Book 中的模式:https://github.com/paf31/purescript-book/blob/master/text/chapter12.md

exports.fooImpl = function(onSuccess, onFailure) {
    return function() {
        require('some-lib').doThing(function(error, data) {
            if (error) onFailure(error.code)()
            else onSuccess(data)();
        }

    }
}

纯脚本定义:

foreign import fooImpl
  :: Fn2 
      (String -> Effect Unit)
      (ErrorCode -> Effect Unit)
      (Effect Unit)

foo:: (Either ErrorCode String -> Effect Unit) -> Effect Unit
foo path k =
  runFn3 readFileImpl
         path
         (k <<< Right)
         (k <<< Left)

现在如果我跳进 REPL

pulp repl 

并尝试调用我的函数,当我尝试调用所需的库时出现错误。 .xxx is not a function

但是,如果我通过pulp run 运行,一切都会按预期运行,并且调用节点库函数没有问题。

同样,如果我运行节点 repl 并直接调用库,我同样不会遇到任何问题。

有趣的是,并非所有节点库都有这个问题。像fs 这样的内置插件工作正常,但第三方插件在repl 中有问题。

有没有办法让这些库在 REPL 中运行时可用?

【问题讨论】:

    标签: purescript


    【解决方案1】:

    你有一个可重现的例子吗?这个对我有用。我将以https://github.com/nonbili/purescript-msgpack-msgpack 为例。在 repo 目录下启动pulp repl

    PSCi, version 0.12.5
    Type :? for help
    
    > import Msgpack
    > encode' { x: 1 }
    "¡x\1"
    
    

    encode'的实现是

    -- Msgpack.purs
    foreign import encodeToString_ :: Json -> String
    encode' :: forall a. EncodeJson a => a -> String
    encode' = encodeToString_ <<< encodeJson
    
    // Msgpack.js
    var msgpack = require("@msgpack/msgpack");
    
    exports.encodeToString_ = function(json) {
      return uint8ArrayToString(msgpack.encode(json));
    };
    

    【讨论】:

      【解决方案2】:

      我认为这是用户错误导致名称冲突。

      编辑:

      我现在意识到这纯粹是由我的 模块 名称驱动的。只要这不与node_modules 库冲突,一切似乎都很好。

      意思是,即使你直接在文件系统上隐藏名称。比如

      npm install SomeLibrary
      
      node_modules/SomeLibrary/
      

      并且有一个与名称一致的纯脚本目录结构

      src/SomeLibrary/SomeLibrary.js
      src/SomeLibrary/SomeLibrary.purs
      src/main
      

      只要 Purs 文件中的 module 名称与 node_modules 库名称 1:1 不匹配,一切都会好起来的

      module SomeLibraryPurescript where ... 
      

      好的。而

      module SomeLibrary where ...
      

      失败

      我在 purescript 中创建了一个隐藏 node_modules 名称的文件结构。

      src/MyLibrary/MyLibrary.js
      src/MyLibrary/MyLibrary.purs
      src/Main.purs 
      

      当 purescript 填充 .psci_modules 时,它正在拉入我的 MyLibrary 模块,这似乎阻止了它找到 实际 node_modules 模块。

      我修复了这个问题

      1. 清除output/.psci_modules/ 目录
      2. 将我尝试使用 FFI 包装的库移动到 Data/ 目录中
      3. pulp repl

      生成的目录结构:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-07-02
        • 2015-08-02
        • 2017-02-03
        • 2019-07-09
        • 1970-01-01
        • 2014-08-05
        • 1970-01-01
        相关资源
        最近更新 更多