@@ -18,7 +18,8 @@
1818module Language.PureScript.CodeGen.JS (
1919 module AST,
2020 declToJs,
21− moduleToJs
21+ moduleToJs,
22+ wrapExportsContainer
2223) where
2324
2425import Data.Maybe (fromMaybe, mapMaybe)
@@ -55,6 +56,7 @@ moduleToJs opts (Module pname@(ProperName name) decls) env =
5556 (JSBlock (concat $ mapMaybe (\decl -> fmap (map $ optimize opts) $ declToJs opts (ModuleName pname) decl env) (decls))))
5657 [JSAssignment (JSVar name)
5758 (JSBinary Or (JSVar name) (JSObjectLiteral []))]
59+ , JSAssignment (JSAccessor name (JSVar "exports")) (JSVar name)
5860 ]
5961
6062-- |
@@ -325,3 +327,11 @@ statementToJs opts m e (If ifst) = ifToJs ifst
325327 elseToJs (Else sts) = JSBlock (map (statementToJs opts m e) sts)
326328 elseToJs (ElseIf elif) = ifToJs elif
327329statementToJs opts m e (Return value) = JSReturn (valueToJs opts m e value)
330+
331+wrapExportsContainer :: [JS] -> JS
332+wrapExportsContainer modules = JSApp (JSFunction Nothing ["exports"] $ JSBlock $ (JSStringLiteral "use strict") : modules) [exportSelector]
333+ where exportSelector = JSConditional (JSBinary And (JSBinary NotEqualTo (JSTypeOf $ JSVar "module") (JSStringLiteral "undefined")) (JSAccessor "exports" (JSVar "module")))
334+ (JSAccessor "exports" (JSVar "module"))
335+ (JSConditional (JSBinary NotEqualTo (JSTypeOf $ JSVar "window") (JSStringLiteral "undefined"))
336+ (JSAssignment (JSAccessor "PS" (JSVar "window")) (JSObjectLiteral []))
337+ (JSApp (JSFunction Nothing [] $ JSBlock [JSThrow $ JSStringLiteral "PureScript doesn't know how to export modules in the current environment"]) []))