我如何在另一个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 加载的一般文章,讨论了这一点。

源代码合并/预处理

其他回答

最好使用 jQuery 方式. 要延迟已准备的事件,首先拨打 $.holdReady(真实)。

$.holdReady(true);
$.getScript("myplugin.js", function() {
    $.holdReady(false);
});

您也可以使用 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 模块? 有没有替代的浏览器

我没有看到一个答案,你在一个文件中创建一个所有功能和变量的对象,然后在另一个文件中引用这个对象的论点。

例如,您有“jsMod.js”,“jsView”和“jsContr.js”的文件:

文件 jsMod.js

JSMODOBJ = {};
JSMODOBJ.valueAddition = function(/* element value 1 */ val1, /* element value 2 */ val2) {
  return val1 + val2;
}

文件 jsView.js

JSVIEWOBJ = {};
JSVIEWOBJ.elementColour = function(/* element id to change colour */ id, /* css colour classname */ col) {
  document.getElementById(id).className = col;
}

文件 jsContr.js

JSCONTROBJ = {};
var jsMod = JSMODOBJ;
var jsView = JSVIEWOBJ;

JSCONTROBJ.changeColourByValue = function (val1, val2, id, clss) {
  if (jsMod.valueAddition(val1,val2) !== 0) {
    jsView.elementColour(id, clss);
  }
}

然后,您可以通过将脚本插入您的.html 或.php 文件以动态设置.js 文件:

<?php
  echo "<script src = './js/dleafView.js'></script>
        <script src = './js/dleafModule.js'></script>
        <script src = './js/dleafContr.js'></script>";
?>

然后,只需在 <script type="text/javascript"></script> 标签中呼叫控制函数,当然,这在开始时会花费很多时间来设置,但在长期内会节省时间。

我用这个方式有点不同,但这种方式也是有效的。

如果您使用 Angular,那么一个插件模块 $ocLazyLoad 可以帮助您做到这一点。

以下是其文档的一些引用:

加载一个或多个模块和组件有多个文件: $ocLazyLoad.load([‘testModule.js’,‘testModuleCtrl.js’,‘testModuleService.js’]);加载一个或多个模块有多个文件,并在需要时指定一个类型: 注意: 使用需要JS 风格格格格式(例如,从 js! 开始时),不要指定一个文件扩展。

您只能使用要求();标签。

例如,如果我有一个 addition.js 模块,我想添加到 math.js,我会这样做:

//this is math.js

//vars
let a = 1;
let b = 3;

//start of code
const additionfile = require('addition.js');
window.alert("You added " + a + " and " + b + " together, to get " + additionfile.add(a,b) + "!");

如果你想要添加.js 文件,它会看起来像这样的东西

function add(a,b) {
   const sum = a + b;
   return sum;
}