詳解webpack進(jìn)階之插件篇

一、插件篇

我們注重客戶(hù)提出的每個(gè)要求,我們充分考慮每一個(gè)細(xì)節(jié),我們積極的做好成都網(wǎng)站建設(shè)、成都做網(wǎng)站服務(wù),我們努力開(kāi)拓更好的視野,通過(guò)不懈的努力,成都創(chuàng)新互聯(lián)贏得了業(yè)內(nèi)的良好聲譽(yù),這一切,也不斷的激勵(lì)著我們更好的服務(wù)客戶(hù)。 主要業(yè)務(wù):網(wǎng)站建設(shè),網(wǎng)站制作,網(wǎng)站設(shè)計(jì),成都微信小程序,網(wǎng)站開(kāi)發(fā),技術(shù)開(kāi)發(fā)實(shí)力,DIV+CSS,PHP及ASP,ASP.Net,SQL數(shù)據(jù)庫(kù)的技術(shù)開(kāi)發(fā)工程師。

1. 自動(dòng)補(bǔ)全css3前綴

autoprefixer

官方是這樣說(shuō)的:Parse CSS and add vendor prefixes to CSS rules using values from the Can I Use website,也就是說(shuō)它是一個(gè)自動(dòng)檢測(cè)兼容性給各個(gè)瀏覽器加個(gè)內(nèi)核前綴的插件。

舉個(gè)栗子:最新的彈性盒模型flux

實(shí)際代碼:

:fullscreen a {
 display: flex
}

插件自動(dòng)補(bǔ)充后

a {
 display: -webkit-box;
 display: -webkit-flex;
 display: -ms-flexbox;
 display: flex
}

效果顯而易見(jiàn),我們可以更專(zhuān)注于css布局和美化,而不需要花過(guò)多的精力都寫(xiě)相同的外碼而加上不同的前綴,也減少了冗余代碼。

使用方法:

cnpm install --save-dev autoprefixer postcss-loader
var autoprefixer = require('autoprefixer');
module.exports={
 //其他配置這里就不寫(xiě)了

 module:{
 loaders:[
 {
  test:/\.css$/,
  //在原有基礎(chǔ)上加上一個(gè)postcss的loader就可以了
  loaders:['style-loader','css-loader','postcss-loader']
  }
  ]
 },
 postcss:[autoprefixer({browsers:['last 2 versions']})]

}

2. 自動(dòng)生成html插件

html-webpack-plugin

cnpm install html-webpack-plugin --save-dev
 //webpack.config.js
 var HtmlWebpackPlugin = require('html-webpack-plugin');
 module.exports={
 entry:'./index.js',
 output:{
  path:__dirname+'/dist',
  filename:'bundle.js'
 }
 plugins:[
  new HtmlWebpackPlugin()
 ]
 }

作用:它會(huì)在dist目錄下自動(dòng)生成一個(gè)index.html

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

其他配置參數(shù):

{
 entry: 'index.js',
 output: {
 path: 'dist',
 filename: 'bundle.js'
 },
 plugins: [
 new HtmlWebpackPlugin({
  title: 'My App',
  filename: 'admin.html',
  template:'header.html',
  inject: 'body',
  favicon:'./images/favico.ico',
  minify:true,
  hash:true,
  cache:false,
  showErrors:false,
  "chunks": {
  "head": {
  "entry": "assets/head_bundle.js",
  "css": [ "main.css" ]
  },
  xhtml:false
 })
 ]
}
--- header.html ---
<!DOCTYPE html>
<html>
 <head>
 <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
 <title><%= htmlWebpackPlugin.options.title %></title>
 </head>
 <body>
 </body>
</html>

作用:

  1. title: 設(shè)置title的名字  
  2. filename: 設(shè)置這個(gè)html的文件名  
  3. template:要使用的模塊的路徑 
  4. inject: 把模板注入到哪個(gè)標(biāo)簽后 'body',  
  5. favicon: 給html添加一個(gè)favicon  './images/favico.ico',  
  6. minify:是否壓縮  {...} | false (最新api變動(dòng),原來(lái)是ture|false 感謝@onmi指正)
  7. hash:是否hash化 true false ,    
  8. cache:是否緩存,  
  9. showErrors:是否顯示錯(cuò)誤, 
  10. chunks:目前沒(méi)太明白 
  11. xhtml:是否自動(dòng)畢業(yè)標(biāo)簽 默認(rèn)false 

3. 提取樣式插件

extract-text-webpack-plugin

官網(wǎng)是這么解釋的Extract text from bundle into a file.,把額外的數(shù)據(jù)加到編譯好的文件中

var ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
 module: {
  loaders: [
   { test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader") }
  ]
 },
 plugins: [
  new HtmlWebpackPlugin({
    template: './src/public/index.html',
    inject: 'body'
   }),
  new ExtractTextPlugin("[name].[hash].css")
 ]
}

說(shuō)明:將css放到index.html的body上面

4. 拷貝資源插件

copy-webpack-plugin

官方這樣解釋 Copy files and directories in webpack,在webpack中拷貝文件和文件夾

cnpm install --save-dev copy-webpack-plugin
new CopyWebpackPlugin([{
 from: __dirname + '/src/public'
}]),

作用:把public 里面的內(nèi)容全部拷貝到編譯目錄

參數(shù)作用其他說(shuō)明
from定義要拷貝的源目錄from: __dirname + '/src/public'
to定義要烤盤(pán)膛的目標(biāo)目錄from: __dirname + '/dist'
toTypefile 或者 dir可選,默認(rèn)是文件
force強(qiáng)制覆蓋先前的插件可選 默認(rèn)false
context不知道作用可選 默認(rèn) base context 可用 specific context
flatten只拷貝文件不管文件夾默認(rèn)是false
ignore忽略拷貝指定的文件可以用模糊匹配

5. 全局掛載插件

webpack.ProvidePlugin [webpack內(nèi)置插件 ]

new webpack.ProvidePlugin({
 $: "jquery",
 jQuery: "jquery",
 "window.jQuery": "jquery"
}))
new webpack.NoErrorsPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.CommonsChunkPlugin('common.js')

作用: 和上面5個(gè)一一對(duì)應(yīng)

  1.   當(dāng)模塊使用這些變量的時(shí)候,wepback會(huì)自動(dòng)加載。(區(qū)別于window掛載,感謝@lihuanghe121指正)
  2.   不顯示錯(cuò)誤插件
  3.   查找相等或近似的模塊,避免在最終生成的文件中出現(xiàn)重復(fù)的模塊
  4.   丑化js 混淆代碼而用
  5.   提取公共代碼的插件

二、一個(gè)完整的栗子

'use strict';

// Modules
var webpack = require('webpack');
var autoprefixer = require('autoprefixer');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');

/**
 * Env
 * Get npm lifecycle event to identify the environment
 */
var ENV = process.env.npm_lifecycle_event;
var isTest = ENV === 'test' || ENV === 'test-watch';
var isProd = ENV === 'build';

module.exports = function makeWebpackConfig() {
 var config = {};

 config.entry = isTest ? {} : {
  app: './src/app/app.js'
 };

 config.output = isTest ? {} : {
  // Absolute output directory
  path: __dirname + '/dist',

  publicPath: isProd ? '/' : 'http://localhost:8080/',

  filename: isProd ? '[name].[hash].js' : '[name].bundle.js',

  chunkFilename: isProd ? '[name].[hash].js' : '[name].bundle.js'
 };

 if (isTest) {
  config.devtool = 'inline-source-map';
 } else if (isProd) {
  config.devtool = 'source-map';
 } else {
  config.devtool = 'eval-source-map';
 }

 config.module = {
  preLoaders: [],
  loaders: [{
   test: /\.js$/,
   loader: 'babel',
   exclude: /node_modules/
  }, {
   test: /\.css/,
   loader: isTest ? 'null' : ExtractTextPlugin.extract('style', 'css?sourceMap!postcss')
  }, {
   test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/,
   loader: 'file'
  }, {
   test: /\.json$/,
   loader: 'json'
  }, {
   test: /\.scss/,
   loader: 'style!css!sass'
  }, {
   test: /\.html$/,
   loader: 'raw'
  }]
 };
 if (isTest) {
  config.module.preLoaders.push({
   test: /\.js$/,
   exclude: [
    /node_modules/,
    /\.spec\.js$/
   ],
   loader: 'isparta-instrumenter'
  })
 }

 config.postcss = [
  autoprefixer({
   browsers: ['last 2 version']
  })
 ];

 config.plugins = [];
 if (!isTest) {
  config.plugins.push(
   new HtmlWebpackPlugin({
    template: './src/public/index.html',
    inject: 'body'
   }),

   new ExtractTextPlugin('[name].[hash].css', {disable: !isProd})
  )
 }

 if (isProd) {
  config.plugins.push(
   new webpack.NoErrorsPlugin(),

   new webpack.optimize.DedupePlugin(),

   new webpack.optimize.UglifyJsPlugin(),

   new CopyWebpackPlugin([{
    from: __dirname + '/src/public'
   }]),
   new webpack.ProvidePlugin({
    $: "jquery",
    jQuery: "jquery",
    "window.jQuery": "jquery"
   }))
 }

 config.devServer = {
  contentBase: './src/public',
  stats: 'minimal'
 };

 return config;
}();

三、調(diào)試技巧

if (isTest) {
 config.devtool = 'inline-source-map';
}

作用: 使用source-map可以在debug的時(shí)候看到源代碼,方便 查錯(cuò)

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。

分享題目:詳解webpack進(jìn)階之插件篇
鏈接分享:http://muchs.cn/article34/gjgope.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供用戶(hù)體驗(yàn)、服務(wù)器托管、網(wǎng)站設(shè)計(jì)、網(wǎng)站改版、網(wǎng)站策劃、域名注冊(cè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站建設(shè)