webpack從零開始第4課: 插件篇

webpack目錄css


本文參考文檔html

重點插件plugin介紹html5

  • 插件與模塊的功能不同,模塊是爲了導入非es5格式js或其它資源類型文件,定製了一些loader。插件是對最後的打包文件進行處理的,也能夠理解loader是爲打包前作準備,plugin是打包再進行處理
  • 官方插件的使用步驟(內置插件2步)node

    • 配置文件中導入webpack const wp= require('webpack')
    • 在plugins這個數組中加入一個插件實例,new wp.XxxxPlugin({對象})
  • 第三方插件的使用步驟(第3方3步,多一次安裝)webpack

    • 安裝(第三方插件要安裝) 根目錄>cnpm i -D XxxxPlugin
    • 配置文件中導入插件 const XxxxPlugin = require('xxxx-plugin')
    • 在plugins這個數組中加入一個插件實例,new XxxxPlugin({對象})
  • 官方插件有git

    // https://github.com/webpack/webpack/blob/master/lib/webpack.js中exportPlugins部分就是所有內置的插件
    const webpack = require('webpack')
    console.log(webpack ) //這裏能夠看到哪些是webpack內置的插件
      DefinePlugin //定義一個全局常量,如new wp.DefinePlugin({BJ: JSON.stringify('北京'),}),在待打包的js文件中能夠直接使用,如在./src/main.js中console.log('我是在配置文件中定義的'+BJ)
      NormalModuleReplacementPlugin: [Getter],
      ContextReplacementPlugin: [Getter],
      ContextExclusionPlugin: [Getter],
      IgnorePlugin: [Getter],
      WatchIgnorePlugin: [Getter],
      BannerPlugin: [Getter],
      PrefetchPlugin: [Getter],
      AutomaticPrefetchPlugin: [Getter],
      ProvidePlugin: [Getter],
      HotModuleReplacementPlugin: [Getter],
      SourceMapDevToolPlugin: [Getter],
      EvalSourceMapDevToolPlugin: [Getter],
      EvalDevToolModulePlugin: [Getter],
      CachePlugin: [Getter],
      ExtendedAPIPlugin: [Getter],
      ExternalsPlugin: [Getter],
      JsonpTemplatePlugin: [Getter],
      LibraryTemplatePlugin: [Getter],
      LoaderTargetPlugin: [Getter],
      ProgressPlugin: [Getter],
      SetVarMainTemplatePlugin: [Getter],
      UmdMainTemplatePlugin: [Getter],
      NoErrorsPlugin: [Getter],
      NoEmitOnErrorsPlugin: [Getter],
     NewWatchingPlugin: [Getter],
      EnvironmentPlugin: [Getter],
      DllPlugin: [Getter],
      DllReferencePlugin: [Getter],
      LoaderOptionsPlugin: [Getter],
      NamedModulesPlugin: [Getter],
      NamedChunksPlugin: [Getter],
      HashedModuleIdsPlugin: [Getter],
      optimize:
       { AggressiveMergingPlugin: [Getter],
         AggressiveSplittingPlugin: [Getter],
         CommonsChunkPlugin: [Getter],
         ChunkModuleIdRangePlugin: [Getter],
         DedupePlugin: [Getter],
         LimitChunkCountPlugin: [Getter],
         MinChunkSizePlugin: [Getter],
         ModuleConcatenationPlugin: [Getter],
         OccurrenceOrderPlugin: [Getter],
         UglifyJsPlugin: [Getter] }
     }

待講插件清單
下面以webpack.開頭的表示是自帶插件,無須另外安裝
01: webpack.BannerPlugin 加註釋
02: uglifyjs-webpack-plugin 代碼縮小
03: html-webpack-plugin 生成html頁
04: extract-text-webpack-plugin 提取css等github

05: copy-webpack-plugin

插件01 BannerPlugin

做用: 在打包的文件中添加註釋
網址: https://webpack.js.org/plugin...web

/*! 每一次靠近,老是那麼悄悄的 */  //這一行就是使用banner這個插件加入的,利用這個插件能夠加在任何打包後的文件中,如js或css文件
/******/ (function(modules) { // webpackBootstrap
const path = require('path');
const webpack = require('webpack')
module.exports={
    context: path.resolve(__dirname,'../today/wang'),
    entry: {
      home: "./home.js",
    },
    output:{
        path: path.resolve(__dirname, "../dist/"),
        filename: "app.js",  
    },
    watch:true,
    devServer: {
      contentBase: path.join(__dirname, "../dist"),
      //compress: true,
      port: 9000,
      hot:true
    },
    plugins: [
        new webpack.BannerPlugin({ //這是webpack內置的插件,因此不用require導入,可是對於第三方插件要先導入
            banner: '每一次靠近,老是那麼悄悄的'
        })

    ]    
}

插件02 UglifyjsWebpackPlugin

做用: 亂碼,縮小
網址: https://webpack.js.org/plugin...
這個插件不是內置的,要先安裝
1.安裝
D:\03www2018\study\webpack2017>cnpm i -D uglifyjs-webpack-plugin
2.導入
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
3.配置npm

const path = require('path');
const webpack = require('webpack')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
module.exports={
    context: path.resolve(__dirname,'../today/wang'),
    entry: {
      home: "./home.js",
    },
    output:{
        path: path.resolve(__dirname, "../dist/"),
        filename: "app.js",  
    },
    watch:true,
    devServer: {
      contentBase: path.join(__dirname, "../dist"),
      //compress: true,
      port: 9000,
      hot:true
    },
    plugins: [
        new webpack.BannerPlugin({
            banner: '每一次靠近,老是那麼悄悄的'
        }),
        new UglifyJsPlugin()

    ]    
}

如今代碼縮小了,變成segmentfault

!function(e){function t(e){var t=O[e];if(!t)return c;var n=function(r){return t.hot.active?(O[r]?O[r].parents.indexOf(e)<0&&O[r].parents.push(e):(b=[e],u=r),t.children.indexOf(r)<0&&t.children.push(r)):(console.warn("[HMR] unexpected require("+r+") from disposed module "+e),b=[]),c(r)},o=function(e){return{configurable:!0,enumerable:!0,get:function(){return c[e]},set:function(t){c[e]=t}}};for(var a in c)Object.prototype.hasOwnProperty.call(c,a)&&"e"!==a&&Object.defineProperty(n,a,o(a));return n.e=function(e){function t(){_--,"prepare"===x&&(A[e]||i(e),0===_&&0===E&&s())}return"ready"===x&&r("prepare")

插件03 HtmlWebpackPlugin

1.簡單介紹

做用: 用得最多的地方是自動生成入口文件dist/index.html
插件網址: https://webpack.js.org/plugins/html-webpack-plugin/
安裝: cnpm i -D html-webpack-plugin
默認生成文件dist/index.html內容以下

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>webpack App</title>
  </head>
  <body>
    <script src="app.js"></script>
  </body>
</html>

2.配置

// 參考 https://github.com/jantimon/html-webpack-plugin#configuration
...
const HtmlWebpackPlugin = require('html-webpack-plugin')
...
new HtmlWebpackPlugin({
    title: 'hello,零和壹在線課堂', // html5文件中<title>部分
    
    // 關鍵點1: 生成的文件完整名是什麼?是放在哪一個文件夾下?
    // 完整路徑是 output.path+ filename
    
    filename: 'front.html', // 默認是index.html,服務器中設置的首頁是index.html,若是這裏改爲其它名字,那麼devServer.index改成和它同樣
    
    // 關鍵點2: 在哪裏找模板文件, 是 context+template是最後模板的完整路徑,./不能少,path.resolve(context, template)
    template: './template/daqi.html', // 若是以爲插件默認生成的hmtl5文件不合要求,能夠指定一個模板,模板文件若是不存在,會報錯,默認是在項目根目錄下找模板文件,才模板爲樣板,將打包的js文件注入到body結尾處
    inject:'body', // true|body|head|false,四種值,默認爲true,true和body相同,是將js注入到body結束標籤前,head將打包的js文件放在head結束前,false是不注入,這時得要手工在html中加js
            
})
// 關鍵明白2點:在哪裏找模板文件,生成的html5文件又是放在哪裏
// 模板文件位置: context+template
// 生成html5文件位置: output.path+filename

插件04 ExtractTextWebpackPlugin

介紹

做用: 從bundle中提取文本,單獨存一個文件,最經常使用的是將css單獨放在一個文件中,當style樣式比較大時,這個辦法比較好,會加快不少,由於樣式和js能夠同時請求
安裝: D:\03www2018\study\webpack2018>cnpm i -D extract-text-webpack-plugin
官方文檔: https://webpack.js.org/plugin...

配置

const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          fallback: "style-loader",
          use: "css-loader"
        })
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin("styles.css"),
  ]
}

new ExtractTextPlugin的參數,若是是一個字符串,表示提取後生成的css文件名,當webpack-dev-server開啓時,是在內存中

插件05 CopyWebpackPlugin

介紹

做用: 文件拷貝
安裝: 根目錄>cnpm i -D copy-webpack-plugin
官方文檔: https://webpack.js.org/plugins/copy-webpack-plugin/

配置

const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
  plugins: [
    new CopyWebpackPlugin([
    
//from    定義要拷貝的源目錄           from: __dirname + '/src/public'
//to      定義要拷貝到的目標目錄     to: __dirname + '/dist'
//toType  file 或者 dir         可選,默認是文件
//force   強制覆蓋先前的插件           可選 默認false
//context                         可選 默認base context可用specific context
//flatten 只拷貝文件無論文件夾      默認是false
//ignore  忽略拷貝指定的文件           能夠用模糊匹配
            // {output}/file.txt
            { from: 'from/file.txt' },

            // equivalent
            'from/file.txt',

            // {output}/to/file.txt
            { from: 'from/file.txt', to: 'to/file.txt' },

            // {output}/to/directory/file.txt
            { from: 'from/file.txt', to: 'to/directory' },

            // Copy directory contents to {output}/
            { from: 'from/directory' },

            // Copy directory contents to {output}/to/directory/
            { from: 'from/directory', to: 'to/directory' },

            // Copy glob results to /absolute/path/
            { from: 'from/directory/**/*', to: '/absolute/path' },

            // Copy glob results (with dot files) to /absolute/path/
            {
                from: {
                    glob:'from/directory/**/*',
                    dot: true
                },
                to: '/absolute/path'
            },

            // Copy glob results, relative to context
            {
                context: 'from/directory',
                from: '**/*',
                to: '/absolute/path'
            },

            // {output}/file/without/extension
            {
                from: 'path/to/file.txt',
                to: 'file/without/extension',
                toType: 'file'
            },

            // {output}/directory/with/extension.ext/file.txt
            {
                from: 'path/to/file.txt',
                to: 'directory/with/extension.ext',
                toType: 'dir'
            },

            // Ignore some files using glob in nested directory
            {
                from: 'from/directory',
                to: 'to/directory',
                ignore: ['nested/**/*.extension']
            }
        ], {
            ignore: [
                // Doesn't copy any files with a txt extension    
                '*.txt',

                // Doesn't copy any file, even if they start with a dot
                '**/*',

                // Doesn't copy any file, except if they start with a dot
                { glob: '**/*', dot: false }
            ],

            // By default, we only copy modified files during
            // a watch or webpack-dev-server build. Setting this
            // to `true` copies all files.
            copyUnmodified: true
        })
  ]
}
相關文章
相關標籤/搜索