Skip to content

Instantly share code, notes, and snippets.

@sunabozu
Last active November 25, 2015 21:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunabozu/771369c06a89f81c4543 to your computer and use it in GitHub Desktop.
Save sunabozu/771369c06a89f81c4543 to your computer and use it in GitHub Desktop.
'use strict';
var through = require('through2');
var PluginError = require('gulp-util').PluginError;
var reTemplate = /<template>([\s\S]+)<\/template>/i;
var reScript = /<script>([\s\S]+)<\/script>/i;
var reNewLine = /[\n\r\t]+/g;
var reComponent = /Vue\.component\([\s]*[\'\"\`]{1}[\w-]+[\'\"\`]{1},[\s]*\{/;
var reInstance = /new[\s]+Vue[\s]*\([\s\n\r]*\{/;
module.exports = function() {
return through.obj(function(file, encoding, callback) {
if(file.isNull())
return callback(null, file);
if(file.isStream())
this.emit('error', new PluginError(PLUGIN_NAME, 'Streams not supported!'));
//if it's a .vue file
if(file.path.length <= 4 || file.path.substring(file.path.length - 4, file.path.length) !== '.vue')
return callback(null, file);
var strFileContent = String(file.contents);
//dealing with a template tag
var templateContent = reTemplate.exec(strFileContent);
if(templateContent.length < 2) //if there is no template inside the file
return callback(null, file);
templateContent = templateContent[1].replace(reNewLine, '');
//dealing with a script tag
var scriptContent = reScript.exec(strFileContent);
if(scriptContent.length < 2) //if there is no script tag inside the file
return callback(null, file);
scriptContent = scriptContent[1];
var componentMatch = reComponent.exec(scriptContent);
if(!componentMatch) { //if there is no component definition
componentMatch = reInstance.exec(scriptContent);
if(!componentMatch)
return callback(null, file);
}
scriptContent = scriptContent.replace(
componentMatch[0],
componentMatch[0] + '\n\ttemplate: \'' + templateContent + '\',\n'
);
console.log(scriptContent);
//we're fine, return the modified file
file.contents = new Buffer(scriptContent);
//change extension to .js
file.path = file.path.replace(/\.vue$/, '.js');
console.log(file.path);
callback(null, file);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment