天天看點

一步步教你學會browserify

本文來自網易雲社群

作者:孫聖翔

注意

文章需要邊看邊練習,不然你可能忘得速度比看的還快。

原文位址: http://my.oschina.net/goskyblue/blog/552284

Browserify

browserify的官網是http://browserify.org/,他的用途是将前端用到的衆多資源(css,img,js,...) 打包成一個js檔案的技術。

比如在html中引用外部資源的時候,原來我們可能這樣寫

  <script src="/static/libs/landing/js/bootstrap.min.js"></script>
  <script src="/static/libs/landing/js/jquery.flexslider-min.js"></script>
  <script src="/static/libs/landing/js/jquery.nav.js"></script>
  <script src="/static/libs/landing/js/jquery.appear.js"></script>
  <script src="/static/libs/landing/js/headhesive.min.js"></script>
  <script src="/static/libs/jquery/jquery-qrcode/jquery.qrcode.js"></script>
  <script src="/static/libs/jquery/jquery-qrcode/qrcode.js"></script>
  <script src="/static/libs/landing/js/scripts.js"></script>      

但是有了 browserify 的幫助,就可以把這些通通壓縮成一句

<script src="/bundle.js"></script>      

而且不用擔心,jQuery或者underscore等等庫的沖突問題。

雖然這項技術也是最近幾年才流行起來的,但是它迅速的在前端領域流行了起來。另一個跟browserify比較類似的是webpack,但這篇文章不打算介紹它,因為首頁感覺不如browserify做的專業。

安裝

安裝起來很簡單,不過首先你還需要需要先把nodejs裝上。

npm install -g browserify      

借助browserify你可以使用nodejs中常用到的require, module.exports功能。

簡單入門

來個很簡單的例子。

先建立一個hello.js檔案,内容如下

module.exports = 'Hello world';      

然後在建立一個entry.js檔案,内容

var msg = require('./hello.js')console.log("MSG:", msg);      

最後使用browserify進行進行打包

browserify entry.js -o bundle.js      

然後entry.js和hello.js就被打包成一個bundle.js檔案了。

寫一個簡單的index.html驗證下效果

<!DOCTYPE html><html>
    <head>
        <meta charset="utf-8" />
        <title>index</title>
    </head>
    <body>
        <script src="bundle.js"></script>
    </body></html>      

然後用浏覽器打開該檔案,F12開啟調試選項。應該會看到有一句MSG: Hello world被列印出來了。

這就是最簡單的打包應用了。

打包npm中的庫

  1. 先建立一個package.json檔案,内容最簡單的寫下。
     {
         "name": "study_browserify"
     }      
  2. 接着安裝jquery庫
     npm i --save jquery      
    其中--save的意思是将jquery資訊儲存到package.json檔案中。
  3. 修改下我們之前建立的hello.js檔案成
     module.exports = function(){     var $ = require('jquery')
         $(function(){
             $("body").html("Hello world, jquery version: " + $.fn.jquery);
         })
     };      
  4. entry.js檔案也要稍微修改下
     var hello = require('./hello.js')
     hello()      
  5. 檢視效果

    這時打開index.html,你會看到頁面上有字了,出現了Hello world, jquery version ....

    這樣子做的好處有很多,即使這個頁面你又引用了别的jquery也不會和hello.js裡面使用到的沖突。因為打包出來的bundle.js把引用的jquery放到的局部變量裡面。

利用gulp工具自動打包

gulp也是前端開發人員常用的一個工具,用起來效果就像Makefile似的。gulp的首頁是http://gulpjs.com/ 首頁那叫一個簡潔。

gulp的配置檔案是gulpfile.js,按照我提供的内容先建立一個,具體怎麼使用可以之後再去看官網。

var gulp = require('gulp');var rename = require('gulp-rename');var browserify = require('gulp-browserify');

gulp.task('build', function(){    return gulp.src('./entry.js')
        .pipe(browserify({
        }))
        .pipe(rename('bundle.js'))
        .pipe(gulp.dest('./'))
});

gulp.task('default', ['build'], function(){    return gulp.watch(['./*.js', '!./bundle.js'], ['build'])
})      

之後安裝下依賴庫

npm i -g gulpnpm i --save-dev gulp gulp-rename gulp-browserify      

目前目錄下啟動gulp,效果就是每次你修改了js檔案,都會調用browserify打包一次。

打包HTML資源

這個時候用到了另外一個庫 stringify,有了這個庫的幫忙,就可以這麼着用require("./hello.html") 是不是很酷炫。

首先還是安裝 npm i --save-dev stringify

之後需要稍微修改下gulpfile.js

原來這個樣子

gulp.task('build', ['lint'], function(){    return gulp.src('./entry.js')
        .pipe(browserify({ 
        })) 
        .pipe(rename('bundle.js'))
        .pipe(gulp.dest('./'))
});      

增加幾行代碼,需要改造成這樣. 第一行的require可以放到最上面。

var stringify = require('stringify');

gulp.task('build', ['lint'], function(){    return gulp.src('./entry.js')
        .pipe(browserify({
            transform: [
                stringify(['.html']),
            ],  
        })) 
        .pipe(rename('bundle.js'))
        .pipe(gulp.dest('./'))
});      

為了驗證效果。我們添加一個檔案 hello.html

内容簡單的寫下

<strong>Hello</strong><span style="color:blue">World</span>      

接着修改下hello.js,改成

module.exports = function(){    var $ = require('jquery')
    $(function(){
        $("body").html(require('./hello.html'));
    })  
};      

重新打包,并再次重新整理index.html 那個網頁,就可以看到加粗的Hello,以及變藍的World了。

添加靜态代碼檢查

預設情況下,出現的一些低級錯誤,browserify是檢查不到的。此時可以用js比較流行的代碼檢查工具jshint,官網是 http://jshint.com/

jshint相比較jslint配置少了不少,不過依然很多,閑麻煩的話,可以直接用我的。 下面的内容直接儲存為檔案 .jshintrc. 注意前面有個.

{
  "camelcase": true,
  "curly": true,
  "freeze": true,
  "immed": true,
  "latedef": "nofunc",
  "newcap": false,
  "noarg": true,
  "noempty": true,
  "nonbsp": true,
  "nonew": true,
  "undef": true,
  "unused": true,
  "trailing": true,
  "maxlen": 120,
  "asi": true,
  "esnext": true,
  "laxcomma": true,
  "laxbreak": true,
  "node": true,
  "globals": {
    "describe": false,
    "it": false,
    "before": false,
    "beforeEach": false,
    "after": false,
    "afterEach": false,
    "Promise": true
  }}      

之後修改gulpfile.js檔案為

var gulp = require('gulp');var rename = require('gulp-rename');var browserify = require('gulp-browserify');var jshint = require('gulp-jshint');

gulp.task('build', ['lint'], function(){    return gulp.src('./entry.js')
        .pipe(browserify({
        }))
        .pipe(rename('bundle.js'))
        .pipe(gulp.dest('./'))
});

gulp.task('lint', ['jshint'])
gulp.task('jshint', function(){    return gulp.src(['./*.js', '!./bundle.js'])
        .pipe(jshint())
        .pipe(jshint.reporter('jshint-stylish'))
})

gulp.task('default', ['build'], function(){    return gulp.watch(['./*.js', '!./bundle.js'], ['build'])
})      

然後安裝幾個新增的依賴

npm i --save-dev gulp-jshint jshint jshint-stylish      

重新運作gulp, 然後故意把entry.js檔案改的錯一點。你就會發現編輯器開始提示你錯誤了。

後記

不知不覺寫了很多gulp的東西,似乎gulp可以單獨作為一篇文章了。哈哈,先這樣了。

網易雲免費體驗館,0成本體驗20+款雲産品! 

更多網易研發、産品、營運經驗分享請通路網易雲社群。

相關文章:

【推薦】 行為式驗證碼的前景

【推薦】 知物由學 | 廣告欺詐:如何應對數字廣告裡分羹者?

【推薦】 關于網易雲驗證碼V1.0版本的服務介紹

繼續閱讀