如何从已链接的JavaScript文件中导出模块

huangapple go评论99阅读模式
英文:

How to export a module from an linked JavaScript file

问题

在我的项目中,如果我加载 main.js 文件,以下内容可以正常工作:

  1. modules.exports = { property: value }

但是,如果我加载到一个网页中并链接到一个脚本,像这样:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <script src="main.js"></script>
  5. </head>
  6. </html>

然后当我遇到错误时,

  1. ReferenceError: module is not defined
英文:

In my project if I load the main.js file the following works:

  1. modules.exports = { property: value }

But if I load in a web page and it links to a script like so:

  1. &lt;!DOCTYPE html&gt;
  2. &lt;html&gt;
  3. &lt;head&gt;
  4. &lt;script src=&quot;main.js&quot;&gt;&lt;/script&gt;
  5. &lt;/head&gt;
  6. &lt;/html&gt;

Then when I get an error,

  1. ReferenceError: module is not defined

答案1

得分: 1

module.exports 语法是 CommonJS 模块的特性,它是 Node.js 中使用的模块系统,但在 Web 浏览器中不被原生支持。

要使用 ES6 模块,你需要在你的 script 标签上使用 type="module" 属性,就像这样:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <script type="module" src="main.js"></script>
  5. </head>
  6. </html>
英文:

The module.exports syntax is a feature of CommonJS modules, which is a module system used in Node.js but not supported in web browsers natively.

To use ES6 modules, you'll need to use a type="module" attribute on your script tag like this:

  1. &lt;!DOCTYPE html&gt;
  2. &lt;html&gt;
  3. &lt;head&gt;
  4. &lt;script type=&quot;module&quot; src=&quot;main.js&quot;&gt;&lt;/script&gt;
  5. &lt;/head&gt;
  6. &lt;/html&gt;

huangapple
  • 本文由 发表于 2023年5月15日 12:03:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76250809.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定