Last active
December 18, 2015 08:24
-
-
Save mizchi/5ee5cd7d0ca9447b92d5 to your computer and use it in GitHub Desktop.
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
// This is an onetime script to convert sprockets to commonjs | |
// $ npm install glob | |
// $ npm install babel-cli -g | |
// # Move to your Rails root. | |
// $ babel-node sprockets2commonjs.js | |
let glob = require('glob') | |
let fs = require('fs') | |
let path = require('path') | |
const ROOT = "app/assets/javascripts" | |
const coffeeExpr = /#= require (.*)/g; | |
const jsExpr = /\/\/= require (.*)/g; | |
const whitelist = []; | |
function convertSprocketPathToCommonjsPath(root, fpath, spath) { | |
if (/^\./.test(spath)) { | |
return spath; | |
} | |
let relToRoot = path.relative(fpath, root); | |
let rel = path.join(relToRoot, spath).replace(/^(\.\.\/)/, ""); | |
return rel.indexOf("..") > -1 ? rel : "./" + rel; | |
} | |
glob.sync(`${ROOT}/**/*`, {nodir: true}).forEach(f => { | |
let c = fs.readFileSync(f).toString(); | |
const expr = path.extname(f) === ".coffee" ? coffeeExpr : jsExpr; | |
let ret = c.replace(expr, (_, p) => { | |
if (whitelist.find(w => w === p)) { return c;} | |
return `require("${convertSprocketPathToCommonjsPath(ROOT, f, p)}")` | |
}); | |
if (ret != c) { | |
fs.writeFileSync(f, ret) | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment