【问题标题】:Using node modules from fable使用寓言中的节点模块
【发布时间】:2016-08-09 12:25:12
【问题描述】:

我正在尝试在我的寓言代码中导入一个节点模块。作为寓言的新手,我确实预料到会出现这样的问题,并且理解导入流程似乎就是其中之一。我有下面的代码,它编译得很好,但在 Cannot read property 'request' of undefined 语句的行上运行时失败了 printfn

module Session =
    let inline f (f: 'a->'b->'c->'d) = Func<_,_,_,_> f
    [<Import("default","request")>]
    type Http = 
    abstract request : string -> System.Func<obj,obj,obj,unit> -> unit
    let http : Http = failwith "js only"
    let start () = 

       http.request "http://dr.dk" (ff (fun error response body ->
           printfn "%A" body 
       ))
    do  
        start()

【问题讨论】:

  • 我对 fable 了解不多,但是尝试在 null 上调用实例方法似乎是个坏主意 - 我认为您需要给 http 一个适当的值
  • @JohnPalmer 该行代码取自寓言示例。 F# 代码未执行,而是交叉编译为 JS
  • 你能分享生成的 JavaScript 代码吗?我发现这对调试很有帮助
  • @Richard 我已经没有源代码了,更别说转译输出了

标签: f# babeljs fable-f#


【解决方案1】:

我能够让您的示例在 Fable REPL 中工作:

open System
open Fable
open Fable.Core
open Fable.Core.JS
open Fable.Core.JsInterop

type RequestCallback = Func<obj, obj, obj, unit>

type Request = Func<string, RequestCallback, unit>

[<ImportDefault("request")>]
let request : Request = jsNative

let start () = 
    request.Invoke("http://dr.dk", (fun error response body ->
        console.log("error", error)
        console.log("response", response)
        console.log("body", body)
    ))

start ()

这是它生成的 JavaScript:

import request from "request";
import { some } from "fable-library/Option.js";

export function start() {
    request("http://dr.dk", (error, response, body) => {
        console.log(some("error"), error);
        console.log(some("response"), response);
        console.log(some("body"), body);
    });
}

start();

请注意,已经有许多模块的绑定。对于这个特定的任务,我建议使用Fable.Fetch。如果您想要在浏览器和 .NET 中运行的库,请尝试 Fable.SimpleHttp

【讨论】:

  • 是的,5 年前的寓言世界看起来有些不同。从那时起,绑定方面取得了巨大的进步
猜你喜欢
  • 2018-04-01
  • 2015-11-08
  • 2022-12-17
  • 1970-01-01
  • 2021-02-04
  • 2018-03-05
  • 1970-01-01
  • 1970-01-01
  • 2017-04-01
相关资源
最近更新 更多