如何通过 Fable 将 F# 模块的公共函数公开给 Javascript?

Jua*_*ino 1 javascript f# fable-f#

假设我有以下 f# 模块:

module Sample =
    let Add x y = x + y
    let Subtract x y = x - y
Run Code Online (Sandbox Code Playgroud)

如何配置 Fable 或 Webpack,以便当我将 webpack 生成的 bundle.js 文件包含到我的 index.html 中时,我可以从 javascript 调用模块 Sample 的函数,如下所示:

<script>
   var myResult = Sample.Add(2,4)
</script>
Run Code Online (Sandbox Code Playgroud)

谢谢!

Max*_*gel 5

首先,你需要设置 webpack 来生成一个“库”。

在您的 webpack.config.js 中,您的output节点应如下所示:

    output: {
        path: resolve('./output'),
        filename: '[name].js',
        libraryTarget: 'var',
        library: 'EntryPoint'
    },
Run Code Online (Sandbox Code Playgroud)

然后为了公开一个干净的 API 以从 JavaScript 调用,您应该使用一个接口。

type Sample =
    abstract Add : int -> int -> int
    abstract Subtract : int -> int -> int

let private add x y = x + y

let api =
    { new Sample with
        member __.Add x y = add x y // You can call a local function
        member __.Subtract x y = x - y // You can implement the function directly in the interface 
    }
Run Code Online (Sandbox Code Playgroud)

然后从 JavaScript 你可以做这样的事情:

EntryPoint.api.Add(1, 2)
EntryPoint.api.Subtract(1, 2)
Run Code Online (Sandbox Code Playgroud)