how to use react require syntax?

require is not a React api, nor is it a native browser api (for now).

require comes from commonjs and is most famously implemented in node.js, if you have used node.js, you will see requires everywhere.

due to the popularity of require in node, people have built tools which will transform code that is written in nodejs style to be useable on the browser.

there’s a few benefits to using require, it helps you keep your code modular and for some projects it allows you to write isomorphic code (code that runs both on client and server with minimal change)

In order to use require, you will need to use a tool such as webpack or browserify, I will use browserify as an example.

first create an ‘index.js’

require('./app.js');
alert('index works');

then create an app.js

alert('app works');

next install the browserify cli

npm install -g browserify

And call this command in your shell

browserify index.js > bundle.js

Now you will have a bundle.js, in your html page create a

<script src="bundle.js"></script>

And you should see both alerts run

Now you can continue to code, you can add react in your code by doing a

npm install react --save

and then require it in app.js for example

var React = require('react');

React.createClass({
    render: function(){/*Blah Blah Blah*/}
})

Leave a Comment