我如何在另一个JavaScript文件中添加一个JavaScript文件,类似于CSS中的 @import?
当前回答
旧版本的JavaScript没有进口,包括,或要求,所以许多不同的方法对这个问题已经开发。
使用 package.json:
{
"type": "module"
}
export function hello() {
return "Hello";
}
import { hello } from './module.js';
let val = hello(); // val is "Hello";
export function hello() {
return "Hello";
}
此分類上一篇:mjs:
import { hello } from './module.mjs';
let val = hello(); // val is "Hello";
ECMAScript 在浏览器中的模块
<script type="module">
import { hello } from './hello.mjs'; // Or the extension could be just `.js`
hello('world');
</script>
// hello.mjs -- or the extension could be just `.js`
export function hello(text) {
const div = document.createElement('div');
div.textContent = `Hello ${text}`;
document.body.appendChild(div);
}
在浏览器中的动态进口
<script type="module">
import('hello.mjs').then(module => {
module.hello('world');
});
</script>
Node.js 需要
// mymodule.js
module.exports = {
hello: function() {
return "Hello";
}
}
// server.js
const myModule = require('./mymodule');
let val = myModule.hello(); // val is "Hello"
您可以使用 AJAX 通话加载额外的脚本,然后使用 eval 运行它. 这是最简单的方式,但由于 JavaScript Sandbox 安全模式而仅限于您的域名。
fetchInject([
'https://cdn.jsdelivr.net/momentjs/2.17.1/moment.min.js'
]).then(() => {
console.log(`Finish in less than ${moment().endOf('year').fromNow(true)}`)
})
jQuery 图书馆在一个行中提供充电功能:
$.getScript("my_lovely_script.js", function() {
alert("Script loaded but not necessarily executed.");
});
下面是如何工作的例子:
function dynamicallyLoadScript(url) {
var script = document.createElement("script"); // create a script DOM node
script.src = url; // set its src to the provided URL
document.head.appendChild(script); // add it to the end of the head section of the page (could change 'head' to 'body' to add it to the end of the body section instead)
}
var js = document.createElement("script");
js.type = "text/javascript";
js.src = jsFilePath;
document.body.appendChild(js);
var s = new MySuperObject();
Error : MySuperObject is undefined
function loadScript(url, callback)
{
// Adding the script tag to the head as suggested before
var head = document.head;
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// Then bind the event to the callback function.
// There are several events for cross browser compatibility.
script.onreadystatechange = callback;
script.onload = callback;
// Fire the loading
head.appendChild(script);
}
然后,你写下你想要使用的代码后,脚本被加载到一个Lambda函数:
var myPrettyCode = function() {
// Here, do whatever you want
};
loadScript("my_lovely_script.js", myPrettyCode);
请注意,在 DOM 已加载后,脚本可以运行,或者在此之前,取决于浏览器,以及您是否包含了行 script.async = false;. 有一个关于JavaScript 加载的一般文章,讨论了这一点。
源代码合并/预处理
其他回答
在JavaScript中实施模块有几种方式,这里有两个最受欢迎的方式:
ES6 模块
浏览器还不支持这个模块化系统,所以为了你使用这个合成,你必须使用一个包装,如Webpack. 使用一个包装是更好的,因为这可以将所有的不同的文件融入一个单一(或一对相关的)文件。
// main.js file
export function add (a, b) {
return a + b;
}
export default function multiply (a, b) {
return a * b;
}
// test.js file
import {add}, multiply from './main'; // For named exports between curly braces {export1, export2}
// For default exports without {}
console.log(multiply(2, 2)); // logs 4
console.log(add(1, 2)); // logs 3
CommonJS(在 Node.js 中使用)
这个模块化系统在 Node.js 中使用,你基本上将你的出口添加到一个被称为 module.exports 的对象,然后你可以通过一个要求(‘modulePath’)访问这个对象。
// main.js file
function add (a, b) {
return a + b;
}
module.exports = add; // Here we add our 'add' function to the exports object
// test.js file
const add = require('./main');
console.log(add(1,2)); // logs 3
对于 Node.js 而言,这对我来说是最好的!
我在这里尝试了很多解决方案,但没有一个帮助我只是能够在没有改变范围的情况下加载另一个文件。
const fs = require('fs');
eval(fs.readFileSync('file.js') + '');
所以,如果你想要它快,容易......试试这个:
function include(filename)
{
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
head.appendChild(script)
}
import "./path/to/js/file";
是的! OP 提出了一些类似于“@import in CSS”的要求,这正是这样。 它也不是像火箭科学复杂的一些旧方法一样。 至少毫无疑问是最初学友好的方法,但我确信非初学者也喜欢它。
要开始使用 Vite for a vanilla JavaScript 项目,只需安装 Node.js 和 [NPM3,然后做:
npm create vite@latest <your-vanilla-js-app-name> --template vanilla
是G:
npm create vite@latest my-js-app --template vanilla
正如一个侧面注意事项: 还有另一个可能在你的脑海中出现的问题是名称空间问题,例如,如果你在你所包含的文件中使用的名称类似于你已经在当前文件中的名称吗? 但这是JavaScript的性质,对吗? 这不是这个方法的具体问题。
不要忘了查看LAB.js!
<script type="text/javascript">
$LAB.script("jquery-1.8.3.js").wait().script("scripts/clientscript.js");
</script>