gulp+bower體系如何使用browserify調用npm模塊

緣由

前兩天,被問到:“想用的前端庫,bower中沒有,npm中有,怎麼調用?”。(其項目組採用的是yeoman的webapp腳手架,也就是gulp+bower的體系)

這個問題的答案馬上就蹦出來了,browserify和webpack都可以。webpack這個黑魔法打包工具我們先放一邊,我們來討論下browserify。

問題

的確,browserify作爲模塊化打包工具很輕鬆就能解決這個問題,並且,業界也比較推崇browserify+npm的前端架構體系。

但是,在不推翻gulp+bower體系的前提下,如何用正確得姿勢調用到npm中的模塊呢。

於是,本人開始翻閱browserify相關文檔。

思路

browserify的github地址readme上有這樣一段引起了我的注意:

You can just as easily create a bundle that will export a require() function so you can require() modules from another script tag. Here we'll create a bundle.js with the through and duplexer modules.

$ browserify -r through -r duplexer -r ./my-file.js:my-module > bundle.js
Then in your page you can do:

<script src="bundle.js"></script>
<script>
  var through = require('through');
  var duplexer = require('duplexer');
  var myModule = require('my-module');
  /* ... */
</script>

也就是說,可以將模塊打包起來,之後就能在script中通過require的方式進行加載使用。於是,就有了以下的解決方案。

解決方案

描述

gulp+bower開發體系流程不變的前提下,當需要加載npm模塊的時候,使用browserify進行打包,script通過require加載使用。

命令行用法

browserify -r through -r duplexer -r ./my-file.js:my-module > bundle.js

gulp用法

var browserify = require('browserify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');

gulp.task('browserify', () => {
  browserify()
    .require('through')
    .require('duplexer')
    .require('./my-file.js',{expose: 'my-module'})
    .bundle()
    .pipe(source('bundle.js')) 
    .pipe(buffer()) 
    .pipe($.rename('export-bundle.js'))
    .pipe(gulp.dest('./dist/bundles'));
});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章