使用browserify打包React组件

2022-01-12 00:00:00 reactjs javascript gulp browserify

我正在尝试学习 browserify 来管理我的 javascript.我的第一个简单任务是创建一个 react.js 文件,该文件将由 gulp + browserify 生成

I am trying to learn browserify to manage my javascript. My first simple task is to create a react.js file which will be generated by gulp + browserify

var browserify = require('gulp-browserify');

gulp.task('browserify-react', function () {
  return gulp.src('js/react/react.js')
  .pipe(browserify())
  .pipe(rename('react-generated.js'))
  .pipe(gulp.dest('./dist'));
});

在 js/react/我创建了一个文件 react.js ,它只有两个 require 命令:

In js/react/ I created a file react.js which is just two require commands:

var React = require('react');
var ReactDOM = require('react-dom');

我希望新文件 react-generated.js 包含 react 和 react-dom 模块.

I expect that a new file react-generated.js will content a react and react-dom modules.

会生成文件,但是当我尝试在我的项目中使用这个 react-generated.js 时出现两个错误

File will be generated, but when I try to use this react-generated.js in my project I get two errors

ReferenceError: React is not defined
ReferenceError: ReactDOM is not defined

但如果我使用来自 facebook 的 react javascript,那么一切正常,没有错误

But if I use react javascript from facebook, so everything is ok, no errors

<script src="https://fb.me/react-0.14.0.min.js"></script>
<script src="https://fb.me/react-dom-0.14.0.min.js"></script>

问题.当我使用 gulp-browserify 生成 react 组件时,我错过了什么?

Questions. What do I miss when I generate react components by using of gulp-browserify?

推荐答案

您的 react.js 文件/模块未公开您实例化的变量 ReactReactDOM.在节点中,您可以通过修改 module.exports 对象来公开这些方法,如下所示:

Your react.js file/module isn't exposing the variables React and ReactDOM you instantiate. In node, you make these methods public by modifying the module.exports object like so:

module.exports = {
  React: React,
  ReactDOM: ReactDOM
}

相关文章