mirror of
https://github.com/aspnet/JavaScriptServices.git
synced 2025-12-23 10:08:57 +00:00
Add react tag helper. Clean up code and make it more consistent.
This commit is contained in:
@@ -10,6 +10,26 @@ var origJsLoader = require.extensions['.js'];
|
||||
require.extensions['.js'] = loadViaBabel;
|
||||
require.extensions['.jsx'] = loadViaBabel;
|
||||
|
||||
function findReactComponent(options) {
|
||||
var resolvedPath = path.resolve(process.cwd(), options.moduleName);
|
||||
var loadedModule = require(resolvedPath);
|
||||
if (options.exportName) {
|
||||
// If exportName is specified explicitly, use it
|
||||
if (!(options.exportName in loadedModule)) {
|
||||
throw new Error('The module "' + resolvedPath + '" has no export named "' + options.exportName + '"');
|
||||
}
|
||||
return loadedModule[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 {
|
||||
throw new Error('Cannot find React component, because no export name was specified, and the module "' + resolvedPath + '" has no default exported class.');
|
||||
}
|
||||
}
|
||||
|
||||
function loadViaBabel(module, filename) {
|
||||
// Assume that all the app's own code is ES2015+ (optionally with JSX), but that none of the node_modules are.
|
||||
// The distinction is important because ES2015+ forces strict mode, and it may break ES3/5 if you try to run it in strict
|
||||
@@ -25,14 +45,8 @@ function loadViaBabel(module, filename) {
|
||||
|
||||
module.exports = {
|
||||
renderToString: function(callback, options) {
|
||||
var resolvedPath = path.resolve(process.cwd(), options.moduleName);
|
||||
var requestedModule = require(resolvedPath);
|
||||
var component = options.exportName ? requestedModule[options.exportName] : requestedModule;
|
||||
if (!component) {
|
||||
throw new Error('The module "' + resolvedPath + '" has no export named "' + options.exportName + '"');
|
||||
}
|
||||
|
||||
var history = createMemoryHistory(options.baseUrl);
|
||||
var component = findReactComponent(options);
|
||||
var history = createMemoryHistory(options.requestUrl);
|
||||
var reactElement = React.createElement(component, { history: history });
|
||||
var html = ReactDOMServer.renderToString(reactElement);
|
||||
callback(null, html);
|
||||
|
||||
Reference in New Issue
Block a user