导入javascript应用程序库不起作用

时间:2019-12-02 16:29:08

标签: javascript html

我正在尝试导入https://github.com/tkurki/dnssd.js并制作html文件,如下所示:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1">
  <script src="/index.js"></script>
</head>
<body>
  <section>
    <h1>DNS-SD Browser</h1>
    <div id="services"></div>
  </section>


  <script>
  const dnssd = require('dnssd2');

  // advertise a http server on port 4321
  const ad = new dnssd2.Advertisement(dnssd.tcp('http'), 4321);
  ad.start();

  // find all chromecasts
  const browser = dnssd2.Browser(dnssd.tcp('_http'))
    .on('serviceUp', service => console.log("Device up: ", service))
    .on('serviceDown', service => console.log("Device down: ", service))
    .start();
  </script>

</body>
</html>

但是以某种方式它显示了控制台日志中的错误:

未捕获的ReferenceError:在index.js:1上未定义require

未捕获的ReferenceError:在index.js:18上未定义require

我在做什么错了?

index.js包含:

var Advertisement    = require('./lib/Advertisement');
var Browser          = require('./lib/Browser');
var ServiceType      = require('./lib/ServiceType');
var validate         = require('./lib/validate');
var resolve          = require('./lib/resolve');
var NetworkInterface = require('./lib/NetworkInterface');


module.exports = {
  Advertisement:  Advertisement,
  Browser:        Browser,
  ServiceType:    ServiceType,
  tcp:            ServiceType.tcp,
  udp:            ServiceType.udp,
  all:            ServiceType.all,
  validate:       validate,
  resolve:        resolve.resolve,
  resolveA:       resolve.resolveA,
  resolveAAAA:    resolve.resolveAAAA,
  resolveSRV:     resolve.resolveSRV,
  resolveTXT:     resolve.resolveTXT,
  resolveService: resolve.resolveService,
};

2 个答案:

答案 0 :(得分:0)

浏览器不支持require功能

使用requirejs。您也可以将其与jquery

一起使用

您可以从here

了解有关requirejs的信息

答案 1 :(得分:0)

浏览器不支持开箱即用。尝试添加此脚本标记以从其CDN手动导入require。

<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.js"></script>
<script src="/index.js"></script>