Skip to content

Instantly share code, notes, and snippets.

@11joselu
Last active May 10, 2017 08:22
Show Gist options
  • Save 11joselu/e510fad6e767c34aeb10d74fcfe30c56 to your computer and use it in GitHub Desktop.
Save 11joselu/e510fad6e767c34aeb10d74fcfe30c56 to your computer and use it in GitHub Desktop.
Inject imports into another file and export array of routes for gulp
#!/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;
@11joselu
Copy link
Author

Example:

base.js

import Hello from './components/Hello.vue'

export default [{
    path: '/vue/home',
    name: 'home',
    component: Hello
  }
]

another.js

import Another from './clients/developer/components/Another.vue'

export default [
  {
    path: '/vue/developer',
    name: 'developer',
    component: Adios
  }
]

Will generate:

import Hello from '../components/Hello.vue'
import Another from './clients/developer/components/Another.vue'

export default [{
    path: '/vue/home',
    name: 'home',
    component: Hello
  },
{
    path: '/vue/developer',
    name: 'developer',
    component: Adios
  }]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment