Browserify不起作用-为什么? [英] Browserify does not work - why?
问题描述
我将以下代码浏览器化为bundle.js,并将其包含在前端(在加载任何其他.js文件之前)。我的browserify文件就是这样的:
I have the following code that I browserify to bundle.js, that I include (before loading any other .js file) on my front-end. The file I browserify is simply this this:
var firebase = require('firebase')
然后在前端包含的下一个文件中,对该变量调用authorize(),但出现错误是否未定义firebase?
I then call authorize() on this variable, in the next file that is included on the front-end, but I get an error saying firebase is not defined?
推荐答案
Browserify 是一个模块捆绑程序,可让您使用浏览器中的CommonJS (节点)模块。这意味着您的项目必须遵循 CommonJS 约定进行导出( exports
, module.exports
)和导入(要求
)模块。这是一个基本示例:
Browserify is a module bundler that enables you to use CommonJS (Node) modules in your browser. This implies that your project must follow CommonJS conventions to export (exports
, module.exports
) and import (require
) modules. Here is a basic example:
您的模块( module.js )
Your module (module.js)
var foo = function () {
console.log('Foo');
};
var bar = function () {
console.log('Bar');
};
module.exports = {
foo: foo,
bar: bar
};
您的入口点( main.js )
Your entry point (main.js)
var module = require('./module');
module.foo(); // Foo
module.bar(); // Bar
此代码可与Node一起使用,但是您的浏览器无法解释它。这是Browserify有用的地方...
This code will work out-of-the-box with Node, but your browser cannot interpret it. This is where Browserify is useful...
当您运行命令 browserify main.js -o bundle.js
在您的入口点上,Browserify遍历所有依赖项(在此处为 module.js
),并将其加载到捆绑包中。此捆绑包可在您的浏览器中使用,因此您现在可以将其加载到脚本标签中:
When you run the command browserify main.js -o bundle.js
on your entry point, Browserify traverses all your dependencies (here module.js
) and loads them in a bundle. This bundle is usable in your browser, so you can now load it in a script tag:
<script src="bundle.js"></script>
这篇关于Browserify不起作用-为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!