Last active
May 10, 2017 08:22
-
-
Save 11joselu/e510fad6e767c34aeb10d74fcfe30c56 to your computer and use it in GitHub Desktop.
Inject imports into another file and export array of routes for gulp
This file contains hidden or 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
#!/bin/node | |
const through = require('through2'); | |
const ARRAY_REGEX = new RegExp(/(\[).*([\s\t\n]?.*)+(\])/g); | |
const IMPORT_REGEX = new RegExp(/import.+([\'|\"])/g); | |
const OBJECT_REGEX = new RegExp(/(\{).*([\s\t\n]?.*)+(\})/gi); | |
function concatArray(arr: string[], items: string[]): string[] { | |
return arr.concat(items); | |
} | |
function getStringObjectFromArray(str: string) { | |
return str.match(OBJECT_REGEX)[0]; | |
} | |
var injector = () => { | |
let firstFile: any; | |
let routesFile: string[] = []; | |
let importsFile: string[] = []; | |
return through.obj(function (file: any, enc: any, done: any) { | |
if (file.isNull()) { | |
this.push(file); | |
return done(); | |
} | |
if (file.isStream()) { | |
this.push(file); | |
return done(); | |
} | |
let contents = file.contents.toString(); | |
let arrays = contents.match(ARRAY_REGEX); | |
let imports = contents.match(IMPORT_REGEX); | |
if (imports) { | |
importsFile = concatArray(importsFile, imports); | |
} | |
if (arrays) { | |
routesFile.push(getStringObjectFromArray(arrays[0])); | |
} | |
if (!firstFile) { | |
firstFile = file; | |
return done(); | |
} | |
//iterate(firstFile, file, done); | |
this.push(file); | |
return done(); | |
}, function sendBack(cb: any) { | |
importsFile = importsFile | |
.map((x:string) => x.replace('./', '../')); | |
let content = importsFile.join("\n"); | |
let routes = "\n\nexport default [" + routesFile.join(",\n") + "]"; | |
content += routes; | |
firstFile.contents = new Buffer(content); | |
this.push(firstFile); | |
cb(); | |
}); | |
}; | |
export default injector; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example:
base.js
another.js
Will generate: