什么是ReactJS的“需要"功能? [英] what is 'require' function is ReactJS?

查看:49
本文介绍了什么是ReactJS的“需要"功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下面的示例代码为例.

Take the below sample code for example.

require('react-bootstrap-datetimepicker');

...

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

datatimepicker是可以在我自己的代码中使用的第三方库,但是如果我在js中添加一段代码,firebug会告诉我找不到 require .如果我应该翻译一段代码或执行某些操作?非常感谢

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 函数旨在将单独的代码段(模块")添加到当前作用域,而该功能不是直到 ES2015规范之前都是JavaScript/ECMAScript语言的一部分.

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.

因此,此功能不是特定于ReactJS,也不是该语言的一部分,这就是为什么当您尝试在普通浏览器环境中使用Firefox时会引发错误的原因.

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.

使用 require 同步加载模块通常是称为CommonJS的方法的一部分(请参见模块API ,但浏览器却没有;因此您必须自己带来该功能.

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> 标记,携带一个诸如 Browserify Webpack ,或 JSPM ,然后使用单个< script> 标签加载结果.捆绑器会带来自己的模块加载器.
  • 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.

这篇关于什么是ReactJS的“需要"功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆