简体   繁体   English

如何包含文件夹中的所有 .js 文件?

[英]How to include all .js file from a folder?

Is there any function to include all JavaScript files from a folder using JavaScript.是否有任何函数可以使用 JavaScript 包含文件夹中的所有 JavaScript 文件。 Since I'm have plenty if .js file to include.因为我有很多 if .js文件要包含。

This is a really brief way to require all files (node.js-style):这是一个需要所有文件的非常简短的方法(node.js-style):

var fs = require('fs');

// assuming all things are files
fs.readdirSync('path/to/dir').forEach(function(elementName) {
    require('path/to/dir' + elementName);
});

Generally though people will make an index file in the root of the folder that individually requires each file and exports the appropriate fields.通常,尽管人们会在文件夹的根目录中创建一个索引文件,该文件单独需要每个文件并导出相应的字段。

There isn't, as JS cannot read the file system.没有,因为 JS 无法读取文件系统。 You could:你可以:

  • Create an array of filenames创建文件名数组
  • Create a php (or other server-side) script that returns the file list and fetch the list with ajax创建一个 php(或其他服务器端)脚本,返回文件列表并使用 ajax 获取列表

Once you have the list of files, you can load them with JS:获得文件列表后,您可以使用 JS 加载它们:

var js=document.createElement("script");
js.src=url;
document.body.appendChild(js);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM