webpack 插件使用總結

extract-text-webpack-plugin

用途:提取單獨css文件
不使用extract-text-webpack-plugin插件時的寫法:

{
        test: /\.css$/,
        loader: 'style-loader!css-loader'
 },

這時head里會插入style標簽,加入樣式:

Paste_Image.png

dist目錄無單獨css文件:

Paste_Image.png

使用extract-text-webpack-plugin的寫法:

{
       test: /\.css$/,
       loader: ExtractTextPlugin.extract('style-loader','css-loader')
 },

這時可以看到dist目錄下生成了單獨的index.css文件。通過在html中link標簽去引用,即實現了css與js的分離。

看下webpack打包生成的js文件:

/******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};
/******/
/******/    // The require function
/******/    function __webpack_require__(moduleId) {
/******/
/******/        // Check if module is in cache
/******/        if(installedModules[moduleId])
/******/            return installedModules[moduleId].exports;
/******/
/******/        // Create a new module (and put it into the cache)
/******/        var module = installedModules[moduleId] = {
/******/            exports: {},
/******/            id: moduleId,
/******/            loaded: false
/******/        };
/******/
/******/        // Execute the module function

//關鍵:這里為什么要用call?
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/        // Flag the module as loaded
/******/        module.loaded = true;
/******/
/******/        // Return the exports of the module
/******/        return module.exports;
/******/    }
/******/
/******/
/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;
/******/
/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;
/******/
/******/    // __webpack_public_path__
/******/    __webpack_require__.p = "";
/******/
/******/    // Load entry module and return exports
/******/    return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ({

/***/ 0:
/***/ function(module, exports, __webpack_require__) {

    /*
    * @Author: yqy
    * @Date:   2016-12-05 18:33:36
    * @Last Modified by:   yuqy
    * @Last Modified time: 2016-12-08 19:04:52
    */
    
    'use strict';
    // require('./index.scss');
    
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.index = undefined;
    
    __webpack_require__(5);
    
    var index = {
      init: function init() {
        console.log('index');
      }
    };exports.index = index;
    // require('./index.css');

/***/ },

/***/ 5:
/***/ function(module, exports) {

    // removed by extract-text-webpack-plugin

/***/ }

/******/ });
//# sourceMappingURL=index.js.map

可以看到:webpack整個結構是一個立即執行函數:

(function(){
})({0:funciton(){}, 1: function(){}})

webpack把每個模塊整個都分配一個id,放在一個function里面,這個function通常會有2-3個參數,分別是:module, exports, webpack_require,第三個參數webpack_require根據文件里是否引入其他模塊而決定有無這個參數,這些function組合成一個大的對象,或者一個大的函數數組扔給立即執行函數作為參數進去立即執行。

webpack_require這個函數的作用是返回module.exports上的對象。

return {
    exports: {導出的整個對象},
    id: 0,
    loaded: true 
}

commonsChunckPlugin

webpack本身內置了一些插件,還可以通過npm 安裝第三方插件。commonsChunckPlugin就是webpack內置的一個插件。
有關此插件options設置請參考:https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
大致的參數有:
name/names: 傳遞數組的話會多次觸發
filename:
miniChunks:
chunks:
children:
async:
miniSize:

關于miniChunks:
取值范圍:>=2 <=max(chunk),
設置為 Infinity時,文檔里說道:
just creates the commons chunk, but moves no modules into it.
我的理解是設置Infinity以后,會去讀取common對應的數組,只打包這些內容,不會去檢查entry所有文件之間的公共模塊了。

為什么要用commonsChunckPlugin這個插件?
官方用途第一條解釋的好:

Generate an extra chunk, which contains common modules shared between entry points.

下面是我的理解:

假設你有a頁面index.js,b頁面list.js,兩個頁面都需要用到jquery. 于是你分別在a,b頁面require('jquery')。 這時你打包完成的js中,會發現dist/index.js、dist/list.js中都打包了一份jquery。這樣你的整個項目的體積(zip)就會非常大了,因為每個頁面的入口文件里面都有一份重復的jquery。這時commonschunkPlugin就需要引入進來了。同理CSS,也可以抽取公用的模塊。

//這是入口文件,兩個js都require('jquery')
var entry_map = {
  'index': './public/index/index.js',
  'list': './public/list/list.js'
}
 new webpack.optimize.CommonsChunkPlugin({
      name: 'commons',
      filename: 'commons.js'
 })

使用了插件后立刻發現dist目錄下生成了commons.js文件。
commons.js里會定義一個webpackJsonp函數。這是dist/index.js也發生了變化。整個js會用webpackJsonp包裹起來
commonsChunkPlugin 用法

var entry_map = {
  'index': './public/index/index.js',
  'list': './public/list/list.js',
  'common': ['jquery', 'underscore', '']
}

providePlugin

用途:想在所有模塊中不用require就引用某個模塊
這也個是webpack內置插件,我們常用的react, jquery, underscore等常常會配置在這里:

new webpack.ProvidePlugin({
                $: 'jquery',
                jQuery: 'jquery',
                _: 'underscore',
                smallnote: 'smallnote',
                React: 'react',
                ReactDOM: 'react-dom'
            }),

更多插件使用持續更新中~

References

http://www.lxweimin.com/p/e52550354142
http://webpackdoc.com/loader.html
https://webpack.toobug.net/zh-cn/
https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 版權聲明:本文為博主原創文章,未經博主允許不得轉載。 webpack介紹和使用 一、webpack介紹 1、由來 ...
    it筱竹閱讀 11,233評論 0 21
  • GitChat技術雜談 前言 本文較長,為了節省你的閱讀時間,在文前列寫作思路如下: 什么是 webpack,它要...
    蕭玄辭閱讀 12,715評論 7 110
  • webpack 介紹 webpack 是什么 為什么引入新的打包工具 webpack 核心思想 webpack 安...
    yxsGert閱讀 6,501評論 2 71
  • 剛完成一個基于React+Webpack的項目,漸漸地熟悉了Webpack的一些配置,開發過程中用到了不少Webp...
    清曉凝露閱讀 6,943評論 0 8
  • 一、什么是webpack:webpack是一款模塊加載兼打包工具,它可以將js、jsx、coffee、樣式sass...
    冰_心閱讀 2,020評論 0 3