javascript require doesn't work inside html

2019-07-14 04:28发布

I'm writing html code that involves js code. Below a simple example:

<!DOCTYPE html PUBLIC >
<html>
<body>
<h2>Use JavaScript to Change Text</h2>
<p>This example writes "Hello JavaScript!" into an HTML element with id="demo":</p>
<p id="demo"></p>
<script>
    var net     = require('net');
    var sleep   = require('sleep');
    var element = document.getElementById("demo");
    element.innerHTML = "Hello JavaScript!";
    sleep(1)
</script> 

Unfortunately "Hello JavaScript!" doesn't appear when I browse the above file with my browser. Looking inside the debug console I can see the folowing message:

ReferenceError: require is not defined

So it seems that require is not defined inside the html code but I've written a small test.js file as below:

var net = require('net');
var sleep = require('sleep');
sleep.sleep(1)

and then I run it with

node test.js.

No errors, everything works fine, require is available and sleep and net as well. Why the code inside html file doesn't work?

2条回答
Anthone
2楼-- · 2019-07-14 04:53

The reason you are getting ReferenceError: require is not defined is because nowhere in your html page is Require included. Require does not come with your standard JavaScript library. You must include the file on your page so it can be loaded and used.

This can be done by simply adding <script src="myJS.js"></script> in the <head> or <body> tags. The myJS.js file will, of course, be replaced by the require.js file.

The reason it works when you run with node is because Node already has its own module loader.

查看更多
我命由我不由天
3楼-- · 2019-07-14 05:07

Javascript is not the same as node.js

require() is not a part of JavaScript standard and is not supported by browsers out of the box, it is the node.js module system.

You might need to directly include the modules; some of the modules might not work in the browser sandbox context.

Also, tools such as http://browserify.org/ might be useful.

查看更多
登录 后发表回答