f# - 使用寓言中的节点模块

标签 f# babeljs fable-f#

我正在尝试在我的寓言代码中导入一个节点模块。作为寓言的新手,我确实预料到会出现问题,而理解导入流程似乎就是其中之一。我有下面的代码,编译正常但运​​行时失败,Cannot read property 'request' of undefined on the line of the printfn statement

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 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();

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

关于f# - 使用寓言中的节点模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38850702/

相关文章:

.net - 如何使用 F# (.Net) 执行分布式计算

javascript - 如何使用 babel 为我的 js 服务模块实现经过身份验证的 es 7 装饰器

javascript - Karma-Coverage 报告显示代码被覆盖(显然没有被覆盖)

android - 如何设置 fable-elmish-react native 应用程序?

logging - 如何在 F# Fable 中登录 Application Insights?

f# - 我怎样才能做一个简单的elmish路由器?

map - F# - GroupBy 并将函数应用于第二个元组项中的每个属性

f# - 聚合非规范化数据的惯用方式

javascript - 带有 JS 装饰器(第 3 阶段)和 Babel 的 NodeJS JavaScript 项目不起作用

f# - 为什么Fsharp Interactive允许可变变量被闭包捕获?