1

我正在尝试使用带有因子捆绑的 Browserify 在页面上加载特定模块。

这是我组织 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

主页.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>

吞咽文件

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"
    ]
  }
},

构建没问题。但是当我加载主页时发生错误:“找不到模块'home'”

我做错了什么?这是在多页网站上使用 browserify 的好方法吗?

我为整个项目做了一个回购:https ://github.com/JiDai/browserify-multipage

4

0 回答 0