如何使用react需要语法? [英] how to use react require syntax?

查看:78
本文介绍了如何使用react需要语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到很多反应结构的例子用 var React = require('react')语法。当我尝试使用它时,我得到require is not defined。如何使用和设置我的静态项目以使用require语法?

I see lots of examples for react structured with var React = require('react') syntax. When I try and use this I get "require is not defined". How do I use and set up my static project to use require syntax?

更新

实际上我正在寻找一个webpack / browserify配置文件,所以我可以快速开始使用React和CommonJS。我只编写了没有上述构建工具的反应应用程序

In actuality I am looking for a webpack/browserify config file so I can get started with React and CommonJS quickly. I have only written react apps without said build tools

推荐答案

require不是React api,也不是本机浏览器api(现在)。

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

require来自commonjs,最着名的是在node.js中实现,如果你使用了node.js,你会看到无处不在。

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

由于节点中require的普及,人们已经构建了一些工具,可以将以nodejs样式编写的代码转换为可在浏览器上使用。

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.

使用require有一些好处,它可以帮助你保持代码模块化,对于某些项目,它允许你编写同构代码(在客户端和服务器上运行的代码,只需很少的更改)

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)

为了使用require,您需要使用webpack或browserify等工具,我将使用browserify作为示例。

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

首先创建'index.js'

first create an 'index.js'

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

然后创建app.js

then create an app.js

alert('app works');

下次安装browserify cli

next install the browserify cli

npm install -g browserify

并在shell中调用此命令

And call this command in your shell

browserify index.js > bundle.js

现在你将有一个bundle.js,在你的html页面中创建一个

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

然后在app.js中要求它,例如

and then require it in app.js for example

var React = require('react');

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

这篇关于如何使用react需要语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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