我正在尝试在我的寓言代码中导入一个节点模块。作为寓言的新手,我确实预料到会出现问题,而理解导入流程似乎就是其中之一。我有下面的代码,编译正常但运行时失败,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/