Skip to content

Instantly share code, notes, and snippets.

@crookse
Last active November 28, 2019 16:50
Show Gist options
  • Save crookse/9652a590526622e504e6aaf63e75fa25 to your computer and use it in GitHub Desktop.
Save crookse/9652a590526622e504e6aaf63e75fa25 to your computer and use it in GitHub Desktop.
Vue: Automate Your Routing - index.js (index.html, routes.compiled.js)
const http = require('http');
const fs = require('fs');
compileVueRouteComponents();
let server = http.createServer((req, res) => {
// If the request is for an asset, then send the asset and end the response
if (req.url.includes('assets/')) {
res.write(fs.readFileSync(`${__dirname}/${req.url}`));
return res.end();
}
// Tell the client (the browser in our case) we are sending a `text/html` document
res.setHeader('Content-Type', 'text/html');
// Write the contents of our `index.html` file to the response's body
res.write(fs.readFileSync('./index.html'));
// End the response
return res.end();
});
// Start at localhost:3000
server.listen(3000, 'localhost', () => {
console.log('Server stared at localhost:3000');
});
// Compile code like the following for every route component:
//
// import * as my_route_component from "/path/to/my/route_component.vue";
// export { my_route_component };
function compileVueRouteComponents() {
console.log("Compiling Vue route components");
let fileContents = "";
let components = [];
let uniqueId = 0;
let files = fs.readdirSync(`${__dirname}/vue`);
// Write the `import` lines
files.forEach((file) => {
// We don't care about the app.vue file because it doesn't contain any route information
if (file == "app.vue") {
return;
}
let componentName = "";
componentName = (file + '_' + uniqueId).replace(".vue", "");
fileContents += `import * as ${componentName} from "${__dirname}/vue/${file}";\n`;
uniqueId += 1;
components.push(componentName);
});
// Write the `export` block
fileContents += "\nexport default [\n";
components.forEach(component => {
fileContents += ` ${component},\n`;
});
fileContents += "];";
fs.writeFileSync(`${__dirname}/assets/routes.compiled.js`, fileContents);
console.log("Done compiling Vue route components.");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment