我正在尝试使用Browserify和factor-bundle来加载页面上的特定模块。
以下是我组织JS源文件的方法:
bower_compoments
├── jquery/...
├── foundation/...
└── [...]
static/src/js
├── common.js
├── home.js
└── other_page.js
这是我的构建文件夹:
static/build/js
├── main.js // must be loaded on all pages: bundle of bower_compoments + common.js
├── home.js
└── other_page.js
home.html的
<script type="text/javascript" src="static/build/js/main.js"></script>
<script type="text/javascript" src="static/build/js/home.js"></script>
<script>
// Trying to load and execute the module
var home = require('home'); // Raise an error "Module not found"
home();
</script>
other_page.html
<script type="text/javascript" src="static/build/js/main.js"></script>
<script type="text/javascript" src="static/build/js/other_page.js"></script>
gulp文件
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var factor = require('factor-bundle');
gulp.task('build:scripts', function () {
return browserify({
basedir: "static/src/js/",
entries: [
'./common.js',
'./home.js',
'./other_page.js'
],
debug: true
})
.plugin(factor, {
outputs: [
'static/build/js/home.js',
'static/build/js/other_page.js'
]
})
.bundle()
//Pass desired output filename to vinyl-source-stream
.pipe(source('main.js'))
.pipe(gulp.dest('static/build/js/'));
});
关于Browserify的package.son摘录
"browser": {
"jquery": "./bower_components/jquery/dist/jquery.js",
"foundation": "./bower_components/foundation/js/foundation/foundation.js",
"foundation-dropdown": "./bower_components/foundation/js/foundation/foundation.dropdown.js"
},
"browserify": {
"transform": [
"browserify-shim"
]
},
"browserify-shim": {
"jQuery": "$",
"foundation": {
"depends": [
"jquery:$"
]
},
"foundation-dropdown": {
"depends": [
"foundation"
]
}
},
构建正常。但是当我加载主页时发生错误:“找不到模块'主页'”
我做错了什么? 这是在多页面网站上使用browserify的好方法吗?
我为整个项目做了一个回购:https://github.com/JiDai/browserify-multipage