如何在 Pure-Script 中加载外部 JavaScript 文件?
外部导入语句都内联 javascript 代码,但我想从外部文件加载它们。
require您可以使用 ffi包装标准全局 commonjs函数。
foreign import require :: forall a. String -> a
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样导入一个库
-- Tell the compiler the structure of what you're importing.
type MyLibrary = {
add :: Number -> Number -> Number
}
-- Call the require function and import the library.
-- We need an explicit type annotation so the compiler know what's up
myLib = require './mylib' :: MyLibrary
main = do
let x = myLib.add 1 2
doSomethingWith x
Run Code Online (Sandbox Code Playgroud)
请记住,purescript 假定外部库中的函数已被柯里化。如果您需要调用一个带有多个参数的函数,您将需要更多的样板文件 - 即使用 mkFn。
有关如何执行此操作的更多详细信息,请参阅此处。
https://github.com/purescript/purescript/wiki/FFI-tips
旁注 - 在此示例中,“require”被实现为纯函数,但是,如果您使用的库在导入期间执行副作用(不幸的是,这并不罕见),您应该定义一个将requireEff导入包装在有效单子。
| 归档时间: |
|
| 查看次数: |
1121 次 |
| 最近记录: |