我如何在另一个JavaScript文件中添加一个JavaScript文件,类似于CSS中的 @import?
当前回答
我的总体解决方案来自EdgeS的effect.js.st图书馆(我写的)。
无情的插件警报 - 我在其他 stackexchange 网络网站上. 这是一个链接到 https://codereview.stackexchange.com/questions/263764/dynamic-load-css-or-script。
您将使用什么代码或设计来支持CSS和脚本的动态加载?
要求
支持承诺-等待-async 包括错误操作支持负载一次加密,包括重新加载支持负载在头部,身体,或当前的脚本元素支持负载 css,js,mjs 模块或其他脚本类型的支持其他标签特,如 nonce,crossorigin 等
static loadScriptOrStyle(url, options) {
// provenance :<# **Smallscript EdgeS efekt** `efekt.js.st` github libraries #>
// returns :<Promise#onload;onerror>
// options :<# `fIgnoreCache`, `fAppendToHead`, `fUrlIsStyle`, `attrs:{}` #>
const head = document.head; let node = options?.fAppendToBody ? document.body : head;
const url_loader_cache = document.head.url_loader_cache
? head.url_loader_cache
: (head.url_loader_cache = {script:{},link:{}})
const kind = (options?.fUrlIsStyle || /\.css(?:(?:\?|#).*)?$/i.test(url))
? 'link' : 'script';
// check already-loaded cache
if(url_loader_cache[kind][url]) {
const el = url_loader_cache[kind][url];
// support `fIgnoreCache` reload-option; should not use on `head`
if(options?.fIgnoreCache)
el.remove();
else
return(new CustomEvent('cache',{detail:el}));
}
// (re)create and record it
const self = document.currentScript;
const el = url_loader_cache[kind][url] = document.createElement(kind);
const append = (!self || options?.fAppendToHead || options?.fAppendToBody)
? el => node.appendChild(el)
: el => self.parentNode.insertBefore(el, self);
const load = new Promise((resolve, reject) => {
el.onload = e => {e.detail = el;resolve(e)};
el.onerror = e => {e.detail = el;reject(e)};
// `onload` or `onerror` possibly alter `cache` value
// throw(new URIError(`The ${url} didn't load correctly.`))
});
// configure `module` attr, as appropriate
if(/\.mjs(?:(?:\?|#).*)?$/i.test(url))
el.type = 'module'
// configure other attrs as appropriate (referrer, nonce, etc)
for(const key in options?.attrs) {el[key] = attrs[key]}
// trigger it
if(kind === 'link') el.rel = 'stylesheet', el.href = url; else el.src = url;
append(el);
return(load);
}
其他回答
您也可以使用 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 模块? 有没有替代的浏览器
我基本上做如下,创建一个新的元素,并添加它来主导:
var x = document.createElement('script');
x.src = 'http://example.com/test.js';
document.getElementsByTagName("head")[0].appendChild(x);
在 jQuery 中:
// jQuery
$.getScript('/path/to/imported/script.js', function()
{
// Script is now loaded and executed.
// Put your dependent JavaScript code here.
});
使用 ES6 的进口和出口模块与 Node.js 合作
使用.mjs 扩展而不是.js 的名称文件
创建文件
touch main.mjs lib.mjs
主.js
import { add } from './lib.mjs';
console.log(add(40, 2));
英格兰MJ
export let add = (x,y) => {
return x + y
}
跑步
node --experimental-modules main.js
var js = document.createElement("script");
js.type = "text/javascript";
js.src = jsFilePath;
document.body.appendChild(js);
在过去的一项项目中,我很成功地使用ajile进行重复使用的JavaScript文件的进口,我总是希望有一个功能为此建立在JavaScript本身。
推荐文章
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- src和dist文件夹的作用是什么?
- jQuery UI对话框-缺少关闭图标
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?
- 如何使用JavaScript重新加载ReCaptcha ?
- jQuery。由于转义了JSON中的单引号,parseJSON抛出“无效JSON”错误
- 在JavaScript关联数组中动态创建键
- ReactJS和公共文件夹中的图像
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?