javascript 如何在没有 Node.js 的情况下使用 JS require()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21818558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use JS require() without Node.js
提问by Oliver Ni
This is probably a lame question, but how can you achieve the same thing as require()
(Node.js) in regular JavaScript?
这可能是一个蹩脚的问题,但是如何require()
在常规 JavaScript 中实现与(Node.js)相同的功能?
Some help would really be appreciated.
一些帮助将不胜感激。
采纳答案by Benjamin Gruenbaum
There are several services that let you do this.
有多种服务可让您执行此操作。
The most popular is Browserify.
最受欢迎的是Browserify。
Basically, it entails going through the file reading through the syntax tree and converting it to the a style similar to what RequireJS does.
基本上,它需要通过语法树读取文件并将其转换为类似于 RequireJS 所做的样式。
Note that this requires an extra compilation step. (We will eventually get modules in ES6 though so there's that :) )
请注意,这需要额外的编译步骤。(我们最终会在 ES6 中获得模块,所以就是这样:))
回答by Shannon
http://requirejs.org/docs/start.html
http://requirejs.org/docs/start.html
A module loader called RequireJS exists for in-browser use without the use of Node.js or Rhino.
存在一个名为 RequireJS 的模块加载器,可在浏览器中使用,无需使用 Node.js 或 Rhino。
To use it download and save the script and include it in your page
要使用它,请下载并保存脚本并将其包含在您的页面中
<!DOCTYPE html>
<html>
<head>
<title>My Sample Project</title>
<!-- data-main attribute tells require.js to load
scripts/main.js after require.js loads. -->
<script data-main="scripts/main" src="scripts/require.js"></script>
</head>
<body>
<h1>My Sample Project</h1>
</body>
</html>
The data-main attribute will point to your main script where you can load the rest of your scripts using:
data-main 属性将指向您的主脚本,您可以在其中使用以下命令加载其余脚本:
require(["helper/util"], function(util) {
//This function is called when scripts/helper/util.js is loaded.
//If util.js calls define(), then this function is not fired until
//util's dependencies have loaded, and the util argument will hold
//the module value for "helper/util".
});
Checkout the documents at http://requirejs.orgfor more information.
查看http://requirejs.org 上的文档以获取更多信息。