Add react tag helper. Clean up code and make it more consistent.

This commit is contained in:
SteveSandersonMS
2015-11-04 12:19:43 -08:00
parent e410affbd8
commit 7c3d22c7b6
14 changed files with 146 additions and 63 deletions

View File

@@ -3,20 +3,39 @@ var ngUniversal = require('angular2-universal-patched');
var ng = require('angular2/angular2');
var ngRouter = require('angular2/router');
module.exports = {
renderComponent: function(callback, options) {
// Find the component class. Use options.componentExport if specified, otherwise convert tag-name to PascalCase.
var loadedModule = require(path.resolve(process.cwd(), options.componentModule));
var componentExport = options.componentExport || options.tagName.replace(/(-|^)([a-z])/g, function (m1, m2, char) { return char.toUpperCase(); });
var component = loadedModule[componentExport];
if (!component) {
throw new Error('The module "' + options.componentModule + '" has no export named "' + componentExport + '"');
}
function getExportOrThrow(moduleInstance, moduleFilename, exportName) {
if (!(exportName in moduleInstance)) {
throw new Error('The module "' + moduleFilename + '" has no export named "' + exportName + '"');
}
return moduleInstance[exportName];
}
function findAngularComponent(options) {
var resolvedPath = path.resolve(process.cwd(), options.moduleName);
var loadedModule = require(resolvedPath);
if (options.exportName) {
// If exportName is specified explicitly, use it
return getExportOrThrow(loadedModule, resolvedPath, options.exportName);
} else if (typeof loadedModule === 'function') {
// Otherwise, if the module itself is a function, assume that is the component
return loadedModule;
} else if (typeof loadedModule.default === 'function') {
// Otherwise, if the module has a default export which is a function, assume that is the component
return loadedModule.default;
} else {
// Otherwise, guess the export name by converting tag-name to PascalCase
var tagNameAsPossibleExport = options.tagName.replace(/(-|^)([a-z])/g, function (m1, m2, char) { return char.toUpperCase(); });
return getExportOrThrow(loadedModule, resolvedPath, tagNameAsPossibleExport);
}
}
module.exports = {
renderToString: function(callback, options) {
var component = findAngularComponent(options);
var serverBindings = [
ngRouter.ROUTER_BINDINGS,
ngUniversal.HTTP_PROVIDERS,
ng.provide(ngUniversal.BASE_URL, { useValue: options.baseUrl }),
ng.provide(ngUniversal.BASE_URL, { useValue: options.requestUrl }),
ngUniversal.SERVER_LOCATION_PROVIDERS
];