nic*_*las 19 javascript requirejs
是否可以使用requireJS"需要"整个文件夹.
例如,我有一个行为文件夹,其中包含大量行为js文件.我真的希望能够简单地使用require(['behavior/*'],function(){...}); 加载该文件夹中的所有内容,而不是必须使该列表保持最新.一旦压缩和优化,我就会把所有这些文件放在一起,但是对于开发来说,单独使用它们会更容易.
gre*_*reg 24
浏览器中的javascript没有文件系统访问权限,因此无法扫描目录中的文件.如果您使用php或ruby等脚本语言构建应用程序,则可以编写一个扫描目录的脚本,并将文件名添加到require()调用中.
虽然浏览器中的JavaScript不能(也不应该)看到文件系统,但我创建了一个Grunt任务,它将执行此操作.我现在还在努力在这里和那里触摸它,但欢迎你来看看.
https://npmjs.org/package/require-wild
npm install require-wild
在您的情况下,您所要做的就是设置任务的设置
grunt.initConfig({
requireWild: {
app: {
// Input files to look for wildcards (require|define)
src: ["./**/*.js"],
// Output file contains generated namespace modules
dest: "./namespaces.js",
// Load your require config file used to find baseUrl - optional
options: { requireConfigFile: "./main.js" }
}
}
});
grunt.loadNpmTasks("require-wild");
grunt.registerTask('default', ['requireWild']);
Run Code Online (Sandbox Code Playgroud)
然后运行grunt任务.您的文件将被生成.修改您main.js的加载namespaces.js
require(['namespaces'], function () { ... });
因此现在允许模块src使用与grunt的glob模式匹配的依赖关系.
require(['behaviors/**/*'], function (behaviors) { }
这种意识形态假设您有一个有意义的文件结构.
我知道这是旧的,但我想分享我的解决方案:
对于此解决方案,您需要JQuery
1)创建一个bash脚本,列出 "MyDirectory /" 中的所有js文件,并将其保存到"directoryContents.txt":
#!/bin/bash
#Find all the files in that directory...
for file in $( find MyDirectory/ -type f -name "*.js" )
do
fileClean=${file%.js} #Must remove .js from the end!
echo -n "$fileClean " >> MyDirectory/directoryContents.txt
done
Run Code Online (Sandbox Code Playgroud)
MyDirectory/FirstJavascriptFile MyDirectory/SecondJavascriptFile MyDirectory/ThirdJavascriptFile
2)然后在你的客户端JS代码:
.
$.get( "MyDirectory/directoryContents.txt", {}, function( data ) {
var allJsFilesInFolder = data.split(" ");
for(var a=0; a<allJsFilesInFolder.length; a++)
{
require([allJsFilesInFolder[a]], function(jsConfig)
{
//Done loading this one file
});
}
}, "text");
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是这个代码没有在我的其他代码之前完成,所以这是我的扩展答案:
define([''], function() {
return {
createTestMenu: function()
{
this.loadAllJSFiles(function(){
//Here ALL those files you need are loaded!
});
},
loadAllJSFiles: function(callback)
{
$.get( "MyDirectory/directoryContents.txt", {}, function( data ) {
var allJsFilesInFolder = data.split(" ");
var currentFileNum = 0;
for(var a=0; a<allJsFilesInFolder.length; a++)
{
require([allJsFilesInFolder[a]], function(jsConfig)
{
currentFileNum++;
//If it's the last file that needs to be loaded, run the callback.
if (currentFileNum==allJsFilesInFolder.length)
{
console.log("Done loading all configuration files.");
if (typeof callback != "undefined"){callback();}
}
});
}
}, "text");
}
}
});
Run Code Online (Sandbox Code Playgroud)
我最终做的是每次我的Node服务器启动时,它将运行bash脚本,填充directoryContents.txt.然后我的客户端只读取directoryContents.txt作为文件列表,并要求该列表中的每一个.
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
22863 次 |
| 最近记录: |