如何通过 Fable 将 F# 模块的 public 函数公开给 Javascript?
How to expose F# module's public functions to Javascript via Fable?
假设我有以下 f# 模块:
module Sample =
let Add x y = x + y
let Subtract x y = x - y
如何配置 Fable 或 Webpack,以便当我将 webpack 生成的 bundle.js 文件包含到我的 index.html 中时,我可以从 javascript 调用模块示例的函数,例如这个:
<script>
var myResult = Sample.Add(2,4)
</script>
谢谢!
首先需要设置webpack生成一个"library".
在您的 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)
假设我有以下 f# 模块:
module Sample =
let Add x y = x + y
let Subtract x y = x - y
如何配置 Fable 或 Webpack,以便当我将 webpack 生成的 bundle.js 文件包含到我的 index.html 中时,我可以从 javascript 调用模块示例的函数,例如这个:
<script>
var myResult = Sample.Add(2,4)
</script>
谢谢!
首先需要设置webpack生成一个"library".
在您的 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)