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
require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object. require() statement not only allows to add built-in core NodeJS modules but also community-based and local modules.
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.
Its aim is to allow developers to easily create fast user interfaces for websites and applications alike. The main concept of React. js is virtual DOM. It is a tree based on JavaScript components created with React that mimics a DOM tree.
Node. js follows the CommonJS module system, and the built-in require function is the easiest way to include modules that exist in separate files. The basic functionality of require is that it reads a JavaScript file, executes the file, and then proceeds to return the exports object.
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:
<script>
tag, bring a loader such as SystemJS and immediately use it to load your own code.<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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With