JavaScript中有没有类似于CSS中的@import
的东西,允许您将一个JavaScript文件包含在另一个JavaScript文件中?
JavaScript中有没有类似于CSS中的@import
的东西,允许您将一个JavaScript文件包含在另一个JavaScript文件中?
旧版本的JavaScript没有导入,没有包含,也没有要求,所以已经开发了许多不同的方法来解决这个问题.
但自2015年(ES6)以来,JavaScript已经有了在Node中导入模块的ES6 modules个标准.js,most modern browsers也支持它.
为了与旧浏览器兼容,可以使用Webpack和Rollup等构建工具和/或Babel等透明工具.
自v8以来,ECMAScript(ES6)模块已经有supported in Node.js个.5、带--experimental-modules
标志,且自至少 node .js v13.8.0没有国旗.要启用"ESM"(与Node.js以前的CommonJS样式模块系统["CJS"]),您可以在package.json
中使用"type": "module"
,或者将文件的扩展名设为.mjs
.(类似地,如果默认为ESM,则使用Node.js以前的CJS模块编写的模块可以命名为.cjs
.)
使用package.json
:
{
"type": "module"
}
然后module.js
:
export function hello() {
return "Hello";
}
然后main.js
:
import { hello } from './module.js';
let val = hello(); // val is "Hello";
使用.mjs
,您将得到module.mjs
:
export function hello() {
return "Hello";
}
然后main.mjs
:
import { hello } from './module.mjs';
let val = hello(); // val is "Hello";
浏览器已经支持直接加载ECMAScript模块(不需要webpack这样的工具)sinceSafari10.1、Chrome61、Firefox60和Edge16.不需要使用Node.js的.mjs
扩展名;浏览器完全忽略模块/脚本上的文件扩展名.
<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);
}
阅读https://jakearchibald.com/2017/es-modules-in-browsers/页的更多内容
动态导入允许脚本根据需要加载其他脚本:
<script type="module">
import('hello.mjs').then(module => {
module.hello('world');
});
</script>
阅读https://developers.google.com/web/updates/2017/11/dynamic-import页的更多内容
较旧的CJS模块样式,仍广泛用于Node.js是module.exports
/require
系统.
// mymodule.js
module.exports = {
hello: function() {
return "Hello";
}
}
// server.js
const myModule = require('./mymodule');
let val = myModule.hello(); // val is "Hello"
JavaScript还有其他方法可以在不需要预处理的浏览器中包含外部JavaScript内容.
您可以通过AJAX调用加载一个额外的脚本,然后使用eval
来运行它.这是最简单的方法,但由于JavaScriptSandbox 安全模型,它仅限于您的域.使用eval
还打开了漏洞、黑客和安全问题的大门.
与动态导入一样,您可以通过fetch
调用加载一个或多个脚本,使用Fetch Inject库控制脚本依赖项的执行顺序:
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库提供加载功能in one line:
$.getScript("my_lovely_script.js", function() {
alert("Script loaded but not necessarily executed.");
});
您可以将带有脚本URL的脚本标记添加到HTML中.为了避免jQuery的开销,这是一个理想的解决方案.
该脚本甚至可以驻留在不同的服务器上.此外,浏览器还判断代码.可以将<script>
标签注入网页<head>
,或者恰好在结束</body>
标签之前插入.
下面是一个如何工作的示例:
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)
}
此函数将在页面的Head部分的末尾添加一个新的<script>
标记,其中src
属性设置为作为第一个参数提供给函数的URL.
这两种解决方案都在JavaScript Madness: Dynamic Script Loading中进行了讨论和说明.
现在,有一个大问题你必须知道.这样做意味着you remotely load the code美元.现代Web浏览器将加载文件并继续执行当前脚本,因为它们异步加载所有内容以提高性能.(这既适用于jQuery方法,也适用于手动动态脚本加载方法.)
这意味着如果你直接使用这些技巧,you won't be able to use your newly loaded code the next line after you asked it to be loaded,因为它仍将加载.
例如:my_lovely_script.js
包含MySuperObject
:
var js = document.createElement("script");
js.type = "text/javascript";
js.src = jsFilePath;
document.body.appendChild(js);
var s = new MySuperObject();
Error : MySuperObject is undefined
然后点击F5重新加载页面.而且很有效!令人困惑
So what to do about it ?
你可以使用作者在我给你的链接中建议的黑客攻击.总之,对于匆忙的人,他在加载脚本时使用事件来运行回调函数.因此,可以使用远程库将所有代码放入回调函数中.例如:
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 function中后,编写要使用的代码:
var myPrettyCode = function() {
// Here, do whatever you want
};
然后你运行所有这些:
loadScript("my_lovely_script.js", myPrettyCode);
请注意,该脚本可能在加载DOM之后或之前执行,具体取决于浏览器以及您是否包含第script.async = false;
行.有great article on Javascript loading in general分讨论这个.
正如本答案顶部所提到的,许多开发人员在他们的项目中使用构建/转换工具,如Parcel、webpack或Babel,允许他们使用即将到来的JavaScript语法,提供对旧浏览器的向后兼容性,合并文件,缩小,执行代码拆分等.