Running ReactJS.NET with browserify

2019-07-18 13:29发布

问题:

I'm struggling to get Browserify working with the ReactJS .NET MVC setup from the demo page.

Everything works when rendering on the server with a .jsx file (not using require()), but when I use my Browserify bundle I get an error of:

An exception of type 'React.Exceptions.ReactInvalidComponentException' occurred in React.dll but was not handled in user code. Additional information: Could not find a component named 'CommentBox'. Did you forget to add it to App_Start\ReactConfig.cs?

Here is my View:

@Html.React("CommentBox", new
{
    initialData = Model
})
<script src="http://fb.me/react-0.12.2.js"></script>
<script src="src/to/bundle.js"></script>
@Html.ReactInitJavaScript()

ReactInitJavascript() compiles to:

<script>React.render(React.createElement(CommentBox, {"initialData":[{"Author":"Daniel Lo Nigro","Text":"Hello ReactJS.NET World!"},{"Author":"Pete Hunt","Text":"This is one comment"}]}), document.getElementById("react1"));

I assume that CommentBox is not defined because it is not accessible from the Browserify bundle, is there a simple way to expose a component?

I'm running my browserify task on the command-line so any suggestions for that would be helpful.

回答1:

You need to expose the component globally, so that it can be accessed from the server-side code. I haven't tried it with Browserify, but the ReactJS.NET documentation does cover how to do this with Webpack: http://reactjs.net/guides/webpack.html