假设我有以下 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>
谢谢!
最佳答案
首先,您需要设置 webpack 来生成“库”。
在您的 webpack.config.js 中,您的 output
节点应如下所示:
output: {
path: resolve('./output'),
filename: '[name].js',
libraryTarget: 'var',
library: 'EntryPoint'
},
然后,为了公开一个干净的 API 以从 JavaScript 进行调用,您应该使用一个接口(interface)。
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)
关于javascript - 如何通过 Fable 将 F# 模块的公共(public)函数公开给 Javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53997440/