3

如何在 Pure-Script 中加载外部 JavaScript 文件?

外部导入语句都内联了 javascript 代码,但我想从外部文件加载它们。

4

1 回答 1

4

require您可以使用 ffi包装标准的全局 commonjs函数。

foreign import require :: forall a. String -> a

然后你可以像这样导入一个库

-- 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

请记住,purescript 假定外部库中的函数已被柯里化。如果您需要调用带有多个参数的函数,则需要更多样板文件 - 即使用 mkFn。

有关如何执行此操作的更多详细信息,请参见此处。

https://github.com/purescript/purescript/wiki/FFI-tips

旁注 - 在此示例中,“require”作为纯函数实现,但是如果您使用的库在导入期间执行副作用(不幸的是,这种情况并不少见),您应该改为定义一个requireEff将导入包装在Eff 单子。

于 2015-03-06T12:16:00.320 回答