javascript require不能在html内运行 [英] javascript require doesn't work inside html

查看:124
本文介绍了javascript require不能在html内运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写涉及js代码的html代码.下面是一个简单的示例:

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> 

很不幸,您好,JavaScript!"当我使用浏览器浏览上述文件时,没有出现.在调试控制台中查看以下消息:

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

因此,似乎require并未在html代码中定义,但是我编写了一个小的test.js文件,如下所示:

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)

然后我用

node test.js.

没有错误,一切正常,要求可用,并且睡眠和上网也是如此.为什么html文件中的代码不起作用?

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

推荐答案

Javascript与node.js不同

require()不是JavaScript标准的一部分,浏览器不提供现成的支持,它是node.js模块系统.

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.

此外,诸如 http://browserify.org/之类的工具可能会有用.

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

这篇关于javascript require不能在html内运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆