Last active
July 20, 2017 04:12
-
-
Save wegry/75779458c9fe1d71aad69ea17196967a to your computer and use it in GitHub Desktop.
purescript psc 0.9 output webpack loader that allows tree shaking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict" | |
/* | |
* Webpack 2 loader that can take CommonJS output by psc 0.9.1 and convert | |
* it into tree shakable ES6 modules. No transpiling required. | |
*/ | |
const fs = require('fs') | |
const commonJsRequire = /var ([$\w]+) = require\("(.*)"\)/g | |
const moduleExports = /module\.exports = \{(\n( ([$\w]+): ([$\w]+)(, )?\n)*)?\};/m | |
const actualExports = /( ([$\w]+): ([$\w]+)(, )?\n)/g | |
module.exports = function (content) { | |
this.cacheable() | |
const funcs = [ | |
upconvertImports, | |
upconvertExports, | |
upconvertFfiExports | |
] | |
let out = funcs.reduce((prev, curr) => curr(prev), content) | |
console.log(out) | |
return out | |
} | |
function findMatches(regex, content, action) { | |
let current; | |
let updated = content.slice() | |
while ((current = regex.exec(content)) !== null) { | |
updated = action(updated, current) | |
} | |
return updated | |
} | |
function upconvertImports (content) { | |
function action (content, currentImport) { | |
let [commonJsImport, identifier, file] = currentImport | |
return content.replace(commonJsImport, `import * as ${identifier} from "${file}"`) | |
} | |
return findMatches(commonJsRequire, content, action) | |
} | |
function upconvertExports (content) { | |
function action (noop, currentExport) { | |
let [_, __, internalName, externalName] = currentExport | |
if (internalName === externalName) { | |
content = content.replace( | |
`var ${internalName} =`, | |
`export var ${internalName} =`) | |
} | |
else { | |
content += `export var ${externalName} = ${internalName};` | |
} | |
return content.replace(moduleExports, '') | |
} | |
let moduleExporting = moduleExports.exec(content) | |
if (moduleExporting) { | |
let [exportsBlob, _] = moduleExporting | |
return findMatches(actualExports, exportsBlob, action) | |
} | |
return content | |
} | |
function upconvertFfiExports (content) { | |
return content.replace(/^exports\./gm, 'export var ') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment