使用Browserify创建React包
问题描述:
这与here的问题相同,但我不明白答案。所以,我的问题是关于答案。使用Browserify创建React包
答案是你实例
你react.js文件/模块未暴露变量反应, ReactDOM。在节点上,你让这些方法公众对 修改module.exports对象,像这样:
module.exports = { React: React, ReactDOM: ReactDOM }
最后,我的问题是:哪里?“你让这些方法公众”?
答
您正在通过在module.exports
属性上定义这些方法来公开这些方法。举例来说,假设你有一个文件reactExports.js与
var iWontGetThere = 'I am in this module only';
module.exports = { React: React, ReactDOM: ReactDOM }
现在
在另一个文件中,您可以要求这些方法并使用它们,就像这样:
var React = require('reactExports').React;
var SweetComponent = React.createClass({
render: function() {
return (
<div>React is cool and I can use it in here!</div>
);
}
});
module.exports = SweetComponent;
现在想象要渲染SweetComponent在另一个组件中。如果我没有写入module.exports = SweetComponent
,那么在另一个组件中要求使用该模块将不会产生任何效果,因为您将导入一个空对象{}
。 比方说,我试图console.log(React.iWontGetThere);
会发生什么?我会得到一个引用错误,因为它没有与reactExports.js的内容一起导出 - 它只存在于该模块中,但未公开。
这是一个人为的例子,但这里有趣的故事是能够引入封装模块。我建议阅读更多关于节点模块here 和检查出this answer以及。 并制作一些示例以获取它的挂起。
tl; dr:定义变量并且没有module.exports = some_value
语句,则需要相同的文件将默认为空对象。