我如何在另一个JavaScript文件中添加一个JavaScript文件,类似于CSS中的 @import?
当前回答
var s=["Hscript.js","checkRobert.js","Hscript.js"];
for(i=0;i<s.length;i++){
var script=document.createElement("script");
script.type="text/javascript";
script.src=s[i];
document.getElementsByTagName("head")[0].appendChild(script)
};
其他回答
从.mix 文件中的混合文档:
混合文件只是.js 或.css 文件与.mix. 在文件名中. 混合文件只是扩展正常风格或脚本文件的功能,并允许您进口和结合。
以下是一個.mix 檔案的例子,將多個.js 檔案組成一個:
// scripts-global.mix.js
// Plugins - Global
@import "global-plugins/headroom.js";
@import "global-plugins/retina-1.1.0.js";
@import "global-plugins/isotope.js";
@import "global-plugins/jquery.fitvids.js";
混合输出这个作为脚本-global.js 以及作为一个小型版本(脚本-global.min.js)。
注意:我不以任何方式与混合,除了使用它作为一个前端开发工具. 我遇到了这个问题,看到一个混合JavaScript文件在行动(在一个混合板)并有点混淆它(“你可以这样做吗?”我认为自己)。 然后我意识到这是一个应用程序特定的文件类型(有些令人失望,同意)。
您也可以使用 gulp, gulp-concat, gulp-typescript with /// <reference path= 包括:
{
"scripts": {
"gulp": "gulp main"
},
"dependencies": {
"@types/gulp": "^4.0.6",
"@types/gulp-concat",
"@types/gulp-typescript",
"gulp": "^4.0.2",
"gulp-concat": "^2.6.1",
"gulp-resolve-dependencies": "^3.0.1",
"gulp-typescript": "^6.0.0-alpha.1",
"typescript": "^3.7.3"
}
}
文件 src/someimport.ts
class SomeClass {
delay: number;
}
/// <reference path="./someimport.ts" />
someclass = new SomeClass();
someclass.delay = 1;
var gulp = require("gulp");
var concat = require('gulp-concat');
var resolveDependencies = require('gulp-resolve-dependencies');
var ts = require("gulp-typescript");
var tsProject = ts.createProject("tsconfig.json");
gulp.task("main", function() {
return gulp
.src(["src/main.ts"])
.pipe(resolveDependencies({
pattern: /^\s*\/\/\/\s*<\s*reference\s*path\s*=\s*(?:"|')([^'"\n]+)/gm
}))
.on('error', function(err) {
console.log(err.message);
})
.pipe(tsProject())
.pipe(concat('main.js'))
.pipe(gulp.dest("build/"));
});
如果您想针对所有 TypeScript 项目文件而不是仅是 src/main.ts,您可以取代以下文件:
return gulp
.src(["src/main.ts"])
.pipe(resolveDependencies({
...
// -->
return tsProject
.src()
.pipe(resolveDependencies({
...
如果您不想使用 TypeScript,您可以使用此简化 gulpfile.js 并从 package.json 中删除所有包含的 TypeScript:
圖片來源:Gulpfile.js
var gulp = require("gulp");
var concat = require('gulp-concat');
var resolveDependencies = require('gulp-resolve-dependencies');
gulp.task("main", function() {
return gulp
.src(["src/main.js"])
.pipe(resolveDependencies({
pattern: /^\s*\/\/\/\s*<\s*reference\s*path\s*=\s*(?:"|')([^'"\n]+)/gm
}))
.on('error', function(err) {
console.log(err.message);
})
.pipe(concat('main.js'))
.pipe(gulp.dest("build/"));
});
{
"scripts": {
"gulp": "gulp main"
},
"dependencies": {
"gulp": "^4.0.2",
"gulp-concat": "^2.6.1",
"gulp-resolve-dependencies": "^3.0.1"
}
}
class SomeClass {
}
/// <reference path="./someimport.ts" />
someclass = new SomeClass();
someclass.delay = 1;
<html>
<head>
<script src="main.js"></script>
</head>
<body>
<script type="text/javascript">
console.log(someclass.delay);
</script>
</body>
</html>
TypeScript: Gulp 我可以使用 TypeScript 没有 RequireJS? 需要使用 Node.js 上的 Gulp.js 客户端使用另一个 JavaScript 文件的主要文件的简单折叠: 没有折叠的参考错误: 需要没有定义 如何使用 Gulp.js 编写 TypeScript 浏览器 Node.js 模块? 使用 babel 使用文件的折叠 如何在浏览器中“要求” CommonJS 模块? 有没有替代的浏览器
或者,而不是按时包含,请在上传之前使用脚本进行编辑。
我使用Sprockets(我不知道是否有其他人)。您将您的JavaScript代码建立在单独的文件中,并包含由Sprockets引擎处理的评论。
也看:
引入Sprockets:JavaScript依赖管理和折磨
在这里展示的大多数解决方案都意味着动态加载. 我正在寻找一个编译器,将所有依赖的文件集成到一个单一的输出文件. 相同的Less/Sass预处理器处理CSS @import在规则上. 因为我找不到任何值得这个类型的东西,我写了一个简单的工具解决问题。
因此,这里是编译器, https://github.com/dsheiko/jsic,它取代 $import(“文件路径”)与请求的文件内容安全。
主 / 主 / JS
var foo = $import("./Form/Input/Tel");
src / 表格 / 输入 / Tel.js
function() {
return {
prop: "",
method: function(){}
}
}
现在我们可以运行编辑器:
node jsic.js src/main.js build/mail.js
接收合并文件
主 / 主 / JS
var foo = function() {
return {
prop: "",
method: function(){}
}
};
旧版本的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 加载的一般文章,讨论了这一点。
源代码合并/预处理