使用Browserify编译动态所需的模块 [英] Compiling dynamically required modules with Browserify
问题描述
我使用Browserify将大型Node.js应用程序编译成单个文件(使用选项 - 裸
和 - 忽略 - 丢失
[以避免在Express中使用 lib-cov
时出现问题)。我有一些代码可以根据目录中的可用内容动态加载模块:
I am using Browserify to compile a large Node.js application into a single file (using options --bare
and --ignore-missing
[to avoid troubles with lib-cov
in Express]). I have some code to dynamically load modules based on what is available in a directory:
var fs = require('fs'),
path = require('path');
fs.readdirSync(__dirname).forEach(function (file) {
if (file !== 'index.js' && fs.statSync(path.join(__dirname, file)).isFile()) {
module.exports[file.substring(0, file.length-3)] = require(path.join(__dirname, file));
}
});
我的应用程序中出现了奇怪的错误,其中从我编译的目录中加载了aribtrary文本文件文件已加载。我认为这是因为路径不再正确设置,并且因为Browserify将无法 require()
这样动态加载的正确文件。
I'm getting strange errors in my application where aribtrary text files are being loaded from the directory my compiled file is loaded in. I think it's because paths are no longer set correctly, and because Browserify won't be able to require()
the correct files that are dynamically loaded like this.
如果没有制作静态 index.js
文件,是否有一种动态需要目录的首选方法与Browserify开箱即用兼容的模块?
Short of making a static index.js
file, is there a preferred method of dynamically requiring a directory of modules that is out-of-the-box compatible with Browserify?
推荐答案
此插件允许需要Glob模式: require-globify
This plugin allows to require Glob patterns: require-globify
然后,有点破解您可以在编译时添加所有文件而不执行它们:
Then, with a little hack you can add all the files on compilation and not executing them:
// Hack to compile Glob files. Don´t call this function!
function ಠ_ಠ() {
require('views/**/*.js', { glob: true })
}
例如,您可以在需要时要求并执行特定文件:D
And, for example, you could require and execute a specific file when you need it :D
var homePage = require('views/'+currentView)
这篇关于使用Browserify编译动态所需的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!