如何在 Pure-Script 中加载外部 JavaScript 文件?
国外的import语句都是内联javascript代码,但我想从外部文件加载它们。
最佳答案
您可以使用 ffi 包装标准的全局 commonjs require
函数。
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 假定外部库中的函数已被柯里化(Currying)。如果您需要调用一个带有多个参数的函数,您将需要更多样板 - 即使用 mkFn。
有关如何执行此操作的更多详细信息,请参见此处。
https://github.com/purescript/purescript/wiki/FFI-tips
旁注——“require”在此示例中作为纯函数实现,但是如果您使用的库在导入期间执行副作用(不幸的是,这种情况并不少见),您应该定义一个 requireEff
将导入包装在 Eff monad 中的函数。
关于purescript - 在纯脚本中加载外部javascript文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28580743/