javascript - 如何通过 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>
谢谢!
解决方案
首先,您需要设置 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)
推荐阅读
- excel - 使用 Powershell 运行时,宏重命名表将不起作用
- spring-boot - springboot decode % error 当它在 url 中并且已经被转义
- python - 在heroku上提供动态文件?
- sql - 在另外两个表中复制一个表的列
- apache - “授权”:令牌未通过 CORS VUEJS APACHE
- python - 按降序排序python
- python - 为什么 Pymongo 在使用 python 控制台时返回 E11000 重复错误
- class - 为什么类是通过引用传递的,而结构是通过复制传递的?
- postgresql - 在 postgrSQL 中使用主键
- python-3.x - 可视化链接攻击的最佳方法是什么