简体   繁体   English

Browserify不会将module.exports转换为window属性吗?

[英]Browserify doesn't translate module.exports to window property?

I'm very confused by the use-case of browserify at the moment. 我对当前的browserify用例感到非常困惑。 I had always been under the impression that it would take an npm module and make it use-able in the browser. 我一直觉得它需要一个npm模块并使其在浏览器中npm However if I take a standard npm module, run it through browserify, and include it in a webpage, I find the module is completely inaccessible. 但是,如果我使用标准的npm模块,通过browserify运行它,并将其包含在网页中,我会发现该模块完全不可访问。

node module: 节点模块:

console.log('wtf');
function SayHi() {
  return 'hello world';
}
module.exports = SayHi;

run it through browserify: 通过browserify运行它:

browserify test.js > browserify_test.js

Now when I include it in a simple webpage and open the JS console I see: 现在,当我将其包含在一个简单的网页中并打开JS控制台时,我会看到:

"wtf"

however cannot access the module: 但是无法访问该模块:

> SayHi
ReferenceError: SayHi is not defined

in order to access my module I need to add some boilerplate code to my npm module: 为了访问我的模块,我需要向我的npm模块添加一些样板代码:

... (previous test.js code)...
if (typeof window === 'object') {
  window.SayHi = SayHi;
}

now, after passing through browserify and loading the page, I have access to my module: 现在,在通过browserify并加载页面后,我可以访问我的模块了:

"wtf"
> SayHi
function SayHi()
> SayHi()
"hello world"

I thought the whole point of browserify was to make your modules usable in the browser. 我认为browserify的全部目的是使您的模块在浏览器中可用。 Not just run them in a sandbox and not let you get to the module itself. 不只是在沙箱中运行它们,还不让您进入模块本身。 Before I go about adding that boilderplate addition to all my modules, I thought it best to ask here to make sure I'm not missing something fundamental. 在我将Boilderplate添加到所有模块之前,我认为最好在这里进行询问,以确保我没有遗漏一些基本知识。

I also don't see how this is supposed to work in an AMD environment. 我也看不到在AMD环境中应该如何工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM