简体   繁体   English

将一个 JS 文件直接包含在另一个文件中?

[英]Include a JS file directly in another?

Let's say I have two JS files, which are both obviously representative of larger files.假设我有两个 JS 文件,它们显然都代表较大的文件。 The first is root/foo.js :第一个是root/foo.js

let foo = true;

The next is root/foopolice.js .接下来是root/foopolice.js This code depends on root/foo.js , and by itself, it throws an error:此代码依赖于root/foo.js ,它本身会引发错误:

function patrol(){
  if (foo) alert("Found foo"); // ReferenceError

Finally, there is root/index.html , which links the two:最后是root/index.html ,将两者联系起来:

<script src="/foo.js"></script>
<script src="/foopolice.js"></script>
<button onclick="patrol()">Patrol for foo</button>

The question is, how would I "include" the variable defined in root/foo.js directly into root/foopolice.js without combining the two into one?问题是,我如何将root/foo.js中定义的变量直接“包含”到root/foopolice.js而不将两者合二为一? The use of both script tags is not enough, because root/foopolice.js would still warn of a nonexistent error while I edit it.使用这两个脚本标签是不够的,因为当我编辑它时, root/foopolice.js仍然会警告不存在的错误。 I'm open to solutions using JQuery or just vanilla JS, depending on best practice.我愿意接受使用 JQuery 或只是香草 JS 的解决方案,具体取决于最佳实践。

Typically, a build process is used to create a JS bundle that would extract and combine all of the required code from multiple files (see Parcel or ESBuild ).通常,构建过程用于创建一个 JS 包,该包将从多个文件中提取和组合所有必需的代码(请参阅ParcelESBuild )。

Without a build process, modern JS modules (also known as "ES modules") could be imported using <script type="module"> .如果没有构建过程,可以使用<script type="module">导入现代JS 模块(也称为“ES 模块”)。 JQuery can be avoided entirely in 2020 and beyond. JQuery 可以在 2020 年及以后完全避免。

library.js库.js

const name = 'Jane Doe'

export {
  name
}

main.js main.js

import { name } from './library.js'

function sayHello() {
  console.log(`hello ${name}!`)
}

window.addEventListener('DOMContentLoaded', event => {
  document.querySelector('button').addEventListener('click', sayHello)
})

index.html索引.html

<script type="module" src="main.js"></script>

<button>Say Hello</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM