首页 > 解决方案 > 如何通过 Fable 将 F# 模块的公共函数公开给 Javascript?

问题描述

假设我有以下 f# 模块:

module Sample =
    let Add x y = x + y
    let Subtract x y = x - y

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

<script>
   var myResult = Sample.Add(2,4)
</script>

谢谢!

标签: javascriptf#fable-f#

解决方案


首先,您需要设置 webpack 以生成“库”。

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

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

然后为了公开一个干净的 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 
    }

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

EntryPoint.api.Add(1, 2)
EntryPoint.api.Subtract(1, 2)

推荐阅读