事情是这样的,
我来自一个网页中包含几个 js 文件的世界.有些总是包含在页面中(您的库、菜单等...),其他则取决于当前页面(用于登录页面的 js,用于订阅的 js 等...).基本上假设我有 每页 1 个不同的 js 文件加上库.
I come from a world where you have several js files included to a web page. Some are always included in the page (your libs, menu etc...) and others are depending on the current page (js for login page, js for subscription etc...). Basically let's say that I have 1 different js file per page plus the libs.
现在我想用 browserify 开始一个新项目,但我遇到了一个大问题:
Now I want to start a new project with browserify and I am in front of a big problem :
所以我的问题是:
这取决于您的具体情况.Browserify 通常用于单页应用程序,其中单个捆绑包通常是最佳解决方案.您在非单页应用程序中使用它.
It depends on your particular case. Browserify is often used for single page apps where a single bundle is often the best solution. You are using it in a non single-page application.
我看到两个选择:
将所有内容捆绑在一起.如果您有一个相对较小的应用程序,这将是最简单且可能是最有效的解决方案(因为浏览器缓存).只需将所有页面特定模块与其他模块一起包含在内.
Bundle everything together. If you have a relatively small app, this will be the easiest and maybe most efficient solution (because of browser caching). Just include all your page specific modules along with your other ones.
创建单独的捆绑包.您可以为每个页面创建一个包,或为相关页面组创建一个包.Browserify 将为每个包创建一个单独的文件,您可以在每个页面上单独包含它们.
Create separate bundles. You could create a bundle for each page, or a bundle for groups of related pages. Browserify will create a separate file for each bundle and you can include them independently on each page.
<script src="common-bundle.js"></script>
<script src="bundle-for-this-page.js"></script>
您仍然可以跨模块使用 require()
.
You will still be able to use require()
across modules.
您可以将每个页面的 javascript 分离到一个单独的目录中,并使用它来自动化 gulp.使用 gulp 它可能看起来像:
You could separate each page's javascript into a separate directory and use that to automate gulp. With gulp it could look something like:
var pageDirs = ['page1', 'page2'];
pageDirs.forEach(function(pageDir) {
gulp.task('browserify-' + pageDir, function() {
gulp.src(pageDir + '/index.js')
.pipe(browserify())
.on('prebundle', function(bundle) {
bundle.external('./common-bundle');
})
.pipe(gulp.dest('./build/' + pageDir))
});
});
gulp.task('browserify-all', pageDirs.map(function(pageDir) {
return 'browserify-' + pageDir;
});
创建一个单独的任务来浏览你的公共包.
Create a separate task for browserifying your common bundle.
这篇关于大型 Web 项目中 Browserify 的最佳实践 - Gulp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!