一塊兒來了解下這些webpack經常使用插件

前言

對於webpack的配置以及經常使用模塊你們應該都比較熟悉,本文將說一說webpack的一些經常使用插件,以及用法。

目錄

1.內置插件css

名稱 參數 說明 用法
DefinePlugin Object 編譯時配置的全局常量,開發模式和發佈模式的構建容許不一樣的行爲很是有用 DefinePlugin
HotModuleReplacementPlugin - 熱更新模塊
NoEmitOnErrorsPlugin - 打包出錯時不把錯誤輸出到文件
NamedModulesPlugin - 顯示模塊相對路徑
ProvidePlugin - 自動加載模塊 ProvidePlugin
PrefetchPlugin context: 目錄的絕對路徑,request: 模塊路徑 預加載模塊請求

2.其餘插件html

名稱 參數 說明 用法
CopyWebpackPlugin Array 拷貝文件夾或文件到指定目錄 CopyWebpackPlugin
HtmlWebpackPlugin - 在編譯目錄下生成html,並將打包後的js文件插入script標籤中 HtmlWebpackPlugin
ExtractTextPlugin - 把打包文件中的文本提取到一個文件 ExtractTextPlugin
OptimizeCSSPlugin - 優化壓縮css文件 OptimizeCSSPlugin
UglifyJsPlugin - 壓縮JavaScript文件 UglifyJsPlugin
WebpackDevServer 提供了一個簡單的 web server,而且具備 live reloading(實時從新加載) 功能 WebpackDevServer
WebpackHotMiddleware 把 webpack 處理過的文件發送到一個 server webpackHotMiddleware

用法介紹

DefinePlugin

  • 若是這個值是一個字符串,它會被看成一個代碼片斷來使用。
  • 若是這個值不是字符串,它會被轉化爲字符串(包括函數)。
  • 若是這個值是一個對象,它全部的 key 會被一樣的方式定義。
  • 若是在一個 key 前面加了 typeof,它會被定義爲 typeof 調用。
new webpack.DefinePlugin({
  PRODUCTION: JSON.stringify(true),
  VERSION: JSON.stringify('5fa3b9'),
  BROWSER_SUPPORTS_HTML5: true,
  TWO: '1+1',
  'typeof window': JSON.stringify('object'),
  'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
});
console.log('Running App version ' + VERSION);
if(!BROWSER_SUPPORTS_HTML5) require('html5shiv');

ProvidePlugin

自動加載模塊,而沒必要處處 import 或 require 。
任什麼時候候,當 identifier 被看成未賦值的變量時,module 就會自動被加載,而且 identifier 會被這個 module 導出的內容所賦值。(或者被模塊的 property 導出的內容所賦值,以支持命名導出(named export))。html5

new webpack.ProvidePlugin({
  identifier: 'module1',
  // ...
});

new webpack.ProvidePlugin({
  identifier: ['module1', 'property1'],
  // ...
});

對於 ES2015 模塊的 default export,你必須指定模塊的 default 屬性。webpack

CopyWebpackPlugin

拷貝文件夾或文件到指定目錄web

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

module.exports = {
  plugins: [
    new CopyPlugin([
      { from: 'source', to: 'dest' },
      { 
          from: 'other',
          to: 'public',
          ignore: ['*.js'],
          flatten: false,  //僅複製文件。用於文件夾和文件同名時
      },
    ]),
  ],
};https://webpack.docschina.org/plugins/copy-webpack-plugin/#ignore

查看更多express

HtmlWebpackPlugin

該插件將爲你生成一個HTML文件,其中包括使用script標籤中引入webpack打包js。
若是你有多個webpack入口點,他們都會在生成的HTML文件中的script標籤內。
若是你有任何CSS assets在webpack的輸出中(例如,利用MiniCssExtractPlugin提取 CSS),那麼這些將被包含在HTML head中的<link>標籤內。app

new HtmlWebpackPlugin({
      title: 'Webpack App'  //用於生成的HTML文檔的標題 默認爲Webpack App
      filename: 'index.html', //將HTML寫入的文件 默認index.html
      template: 'index.html', //webpack模板的相對或絕對路徑。默認src/index.ejs
      //template: path.resolve(__dirname, '../index.ejs'),
      inject: true, //true || 'head' || 'body' || false  打包後的js引入位置 body/head
      favicon: String,
      meta: Object,
      base: Object|String|false,
      showErrors: Boolean, //將它錯誤信息寫入頁面
    }),

ExtractTextPlugin

把打包文件中的文本提取到一個文件一般用於提取csswebpack-dev-server

//webpack4
module: {
  rules: [
    {
      test: /.css$/,
       use: ExtractTextPlugin.extract({
         fallback: "style-loader",
         use: "css-loader",
         publicPath: "/dist"
       })
    }
  ]
}

plugins: [
   new ExtractTextPlugin({
     filename: "bundle.css",
     disable: false,
     allChunks: true
   })
]

OptimizeCSSPlugin

new OptimizeCssAssetsPlugin({
      assetNameRegExp: /\.optimize\.css$/g,
      cssProcessor: require('cssnano'),
      cssProcessorPluginOptions: {
        preset: ['default', { discardComments: { removeAll: true } }],
      },
      canPrint: true
    })

UglifyJsPlugin

new UglifyJsPlugin({
      uglifyOptions: {
        compress: {
          warnings: false
        }
      },
      sourceMap: true,
      parallel: true
    }),

WebpackDevServer

提供了一個簡單的 web server,而且具備 live reloading(實時從新加載) 功能ide

module.exports = {
    devServer: {
      contentBase: './dist'
    }
  };

查看詳細配置函數

WebpackHotMiddleware

const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');

const app = express();
const config = require('./webpack.config.js');
const compiler = webpack(config);

// 告訴 express 使用 webpack-dev-middleware,
// 以及將 webpack.config.js 配置文件做爲基礎配置
app.use(webpackDevMiddleware(compiler, {
  publicPath: config.output.publicPath
}));

// 將文件 serve 到 port 3000。
app.listen(3000, function () {
  console.log('Example app listening on port 3000!\n');
});

也能夠配合devServer

const WebpackDevServer = require('webpack-dev-server')
    
    const compiler = webpack(webpack.conf)
    hotMiddleware = webpackHotMiddleware(compiler, {
      log: false,
      //path
      heartbeat: 2500
    })
    const server = new WebpackDevServer(
      compiler,
      {
        contentBase: path.join(__dirname, '../'),
        quiet: true,
        before (app, ctx) {
          app.use(hotMiddleware)
          ctx.middleware.waitUntilValid(() => {
            
          })
        }
      }
    )
    server.listen(3000)
相關文章
相關標籤/搜索