我如何在另一个JavaScript文件中添加一个JavaScript文件,类似于CSS中的 @import?
当前回答
对于 Node.js 而言,这对我来说是最好的!
我在这里尝试了很多解决方案,但没有一个帮助我只是能够在没有改变范围的情况下加载另一个文件。
const fs = require('fs');
eval(fs.readFileSync('file.js') + '');
其他回答
您也可以使用 PHP 编写脚本:
文件 main.js.php:
<?php
header('Content-type:text/javascript; charset=utf-8');
include_once("foo.js.php");
include_once("bar.js.php");
?>
// Main JavaScript code goes here
var xxx = require("../lib/your-library.js")
或
import xxx from "../lib/your-library.js" //get default export
import {specificPart} from '../lib/your-library.js' //get named export
import * as _name from '../lib/your-library.js' //get full export to alias _name
您只能使用要求();标签。
例如,如果我有一个 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;
}
若要在 JavaScript 中输入另一个脚本,请使用输入关键字:
import '/src/js/example.js';
// both types of quotes work
import "/src/js/example2.js";
也许这里还有另一种方式!
在 Node.js 中,你可以这样做,就像下面的代码一样!
主持人JS
module.exports = {
log: function(string) {
if(console) console.log(string);
}
mylog: function(){
console.log('just for log test!');
}
}
主.js
const mylog = require('./sub');
mylog.log('Hurray, it works! :)');
mylog.mylog();
雷夫斯
HTTP://requirejs.org/docs/node.html