- if (!cache.compilationStarted) {
- return compile(psModule)
- .then(() => Promise.map(cache.deferred, psModule => {
- if (typeof cache.ideServer === 'object') cache.ideServer.kill()
- return toJavaScript(psModule).then(psModule.load)
- }))
- .catch(error => {
- cache.deferred[0].reject(error)
- cache.deferred.slice(1).forEach(psModule => psModule.reject(true))
- })
- }
-}
-
-// The actual loader is executed *after* purescript compilation.
-function toJavaScript(psModule) {
- const options = psModule.options
- const cache = psModule.cache
- const bundlePath = path.resolve(options.bundleOutput)
- const jsPath = cache.bundle ? bundlePath : psModule.jsPath
-
- debug('loading JavaScript for', psModule.name)
-
- return Promise.props({
- js: fs.readFileAsync(jsPath, 'utf8'),
- psModuleMap: psModuleMap(options, cache)
- }).then(result => {
- let js = ''
-
- if (options.bundle) {
- // if bundling, return a reference to the bundle
- js = 'module.exports = require("'
- + path.relative(psModule.srcDir, options.bundleOutput)
- + '")["' + psModule.name + '"]'
- } else {
- // replace require paths to output files generated by psc with paths
- // to purescript sources, which are then also run through this loader.
- js = result.js
- .replace(requireRegex, (m, p1) => {
- return 'require("' + result.psModuleMap[p1].src + '")'
- })
- .replace(/require\(['"]\.\/foreign['"]\)/g, (m, p1) => {
- return 'require("' + result.psModuleMap[psModule.name].ffi + '")'
- })
- }
-
- return js
- })
-}