Require() function in JavaScript
When I open console of Chrome 14 and type...
require
(or require()
, if that matters)
I get: ReferenceError
.
This means that JavaScript doesn't have that function by default, right? At least on web browsers.
Why I'm talking about that?
I needed Markdown parser for JavaScript.开发者_JS百科What to do?
I, as usually, opened GitHub and searched for it. The first results that matched my needs was this and this.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... :(
Usage for #1 script:
var input = "# Heading\n\nParagraph";
var output = require( "markdown" ).toHTML( input );
print( output );
Usage for #2 script:
var marked = require('marked');
console.log(marked('i am using __markdown__.'));
Where does that require()
came from? Thanks in an advice! :)
It's a way to include node.js packages. 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 file in a <script>
tag and you should be able to use the markdown
object from the global scope.
From the page you link to:
The simple way to use it with CommonJS is:
Looks like require
comes from CommonJS
精彩评论