JavaScript 中的 Require() 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7729511/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:21:32  来源:igfitidea点击:

Require() function in JavaScript

javascriptfunctionreferencemarkdownrequire

提问by daGrevis

When I open console of Chrome 14 and type...

当我打开 Chrome 14 的控制台并输入...

require(or require(), if that matters)

require(或者require(),如果这很重要)

I get: ReferenceError.

我得到:ReferenceError

This means that JavaScript doesn't have that function by default, right? At least on web browsers.

这意味着 JavaScript 默认没有这个功能,对吧?至少在网络浏览器上。

Why I'm talking about that?
I needed Markdown parser for JavaScript.

我为什么要谈论那个?
我需要 JavaScript 的 Markdown 解析器。

What to do?
I, as usually, opened GitHub and searchedfor it. The first results that matched my needs was thisand this.

该怎么办?
我像往常一样打开 GitHub 并搜索它。符合我需求的第一个结果是thisthis

Usually (I'm not that good with JavaScript) I include script I want to use before my code using <script />tag and then... well - use it. But this time I don't get what's happening... :(

通常(我对 JavaScript 不太擅长)我在使用<script />标记的代码之前包含了我想使用的脚本,然后......好吧 - 使用它。但这一次我不明白发生了什么...... :(

Usage for #1 script:

#1 脚本的用法:

var input = "# Heading\n\nParagraph";
var output = require( "markdown" ).toHTML( input );
print( output );

Usage for #2 script:

#2 脚本的用法:

var marked = require('marked');
console.log(marked('i am using __markdown__.'));

Where does that require()came from? Thanks in an advice! :)

这是require()从哪里来的?感谢您的建议!:)

回答by Alex Turpin

It's a way to include node.jspackages. Luckily, the first package you linked to, markdown-js, is very smart. It checks whether it is included as a node package, and if not, will set the markdown object to window.markdown. So all you have to do is include this filein a <script>tag and you should be able to use the markdownobject from the global scope.

这是一种包含node.js包的方法。幸运的是,您链接到的第一个包markdown-js非常聪明。它会检查它是否作为节点包包含在内,如果没有,则将 markdown 对象设置为window.markdown. 所以你所要做的就是将这个文件包含在一个<script>标签中,你应该能够使用markdown全局范围内的对象。

回答by Quentin

From the page you link to:

从您链接到的页面:

The simple way to use it with CommonJS is:

在 CommonJS 中使用它的简单方法是:

Looks like requirecomes from CommonJS

看起来像是require来自CommonJS