Skip to content

Instantly share code, notes, and snippets.

@blackmiaool
Last active March 29, 2017 08:42
Show Gist options
  • Save blackmiaool/879b250fc512ad0c7a94160c04b3ee49 to your computer and use it in GitHub Desktop.
Save blackmiaool/879b250fc512ad0c7a94160c04b3ee49 to your computer and use it in GitHub Desktop.
import2require (copy to console to execute)
var test = `
import a from b;
import {a,b} from c;
import a,b,{c,d},{e,f} from c;
import a,{
b,
c,} from d;
alert("hi!");
`;
function import2require(input) {
let output = "";
input = input.replace(/import([\s\S]+?)from([\s\S]+?);\n?/gm, function(match, to, from) {
to = to.replace(/[\n\s]/g, "");
from = from.replace(/[\n\s]/g, "");
to = to.replace(/{([\s\S]+?)}/g, function(match, content) {
output += `const ${match}=require(${from});\n`;
return "";
});
to.split(",").filter(function(part) {
return part;
}).forEach(function(part) {
output += `const ${part}=require(${from});\n`;
});
return "";
});
return output + input;
}
console.log(import2require(test));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment