7

Take the below sample code for example.

require('react-bootstrap-datetimepicker');

...

render: function() {
  return <DateTimeField />;
}

The datatimepicker is a third party library that can be used in my own code, but if I add the piece of code in the js, the firebug will tell me that the require can not be found. If I should translate the piece of code or do something? Thanks very much

liam xu
  • 2,892
  • 10
  • 42
  • 65
  • 1
    JS ecosystem has several competing module systems, some of which work on the fly, some that require preprocessing. This particular sample would, for example, work with Browserify workflow, where Browserify would "compile" all of your JS files into one. – Amadan Sep 17 '15 at 06:16

2 Answers2

6

The require function is intended to add separate pieces of code (“modules”) to the current scope, a feature that was not part of the JavaScript/ECMAScript language until the ES2015 specification.

Therefore this function is not specific to ReactJS, and is not part of the language either, which is why Firefox throws an error when you attempt to use it in a vanilla browser environment.

Using require to load modules synchronously is generally part of a method known as CommonJS (see this answer for more on module formats). While an environment such as Node.js provides a module API similar to this specification, browsers do not; so you must bring the function yourself.

There are many options to do so, and it is up to you to pick the one that best suits your workflow and personal taste. But overall, the patterns come down to either:

  • Explicitly use a module loader in the browser: using a <script> tag, bring a loader such as SystemJS and immediately use it to load your own code.
  • Bundle your code to a single script: using a bundler such as Browserify, Webpack, or JSPM, and load the results using a single <script> tag. The bundler brings along its own module loader.

Generally, the second option is more targeted at production environments, while the first option is more practical in development environments.

Community
  • 1
  • 1
Eric Redon
  • 1,712
  • 12
  • 21
1

You can Do

npm install -g requirejs

then

var requirejs = require('requirejs');
VizardCrawler
  • 1,343
  • 10
  • 16