Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require() function in JavaScript

Tags:

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.

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! :)

like image 650
daGrevis Avatar asked Oct 11 '11 16:10

daGrevis


People also ask

What is require () in NodeJS?

Node.js follows the CommonJS module system, and the builtin require function is the easiest way to include modules that exist in separate files. The basic functionality of require is that it reads a JavaScript file, executes the file, and then proceeds to return the exports object. An example module: console.

Can we use require in JavaScript?

“Require” is built-in with NodeJSWith require , you can include them in your JavaScript files and use their functions and variables. However, if you are using require to get local modules, first you need to export them using module.

For what require function is used?

require keyword refers to a function which is used to import all the constructs exported using the module. exports object from another module. If you have a module x in which you are exporting some constructs using the module.

How do I require a JavaScript file?

To include the Require. js file, you need to add the script tag in the html file. Within the script tag, add the data-main attribute to load the module. This can be taken as the main entry point to your application.


2 Answers

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.

like image 123
Alex Turpin Avatar answered Sep 19 '22 22:09

Alex Turpin


From the page you link to:

The simple way to use it with CommonJS is:

Looks like require comes from CommonJS

like image 29
Quentin Avatar answered Sep 20 '22 22:09

Quentin