Webpack Advanced Plug-in chapter

Source: Internet
Author: User

One, plug-in Chapter 1. Auto complement CSS3 Prefix

Autoprefixer

This is what the authorities say:Parse CSS and add vendor prefixes to CSS rules using values from the Can I Use website
, which means that it is a plug-in that automatically detects compatibility and adds a kernel prefix to each browser.

For a chestnut: The latest elastic box model flux
Actual code:

:fullscreen a {    display: flex}

After the plugin is automatically replenished

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

The effect is obvious, we can focus more on CSS layout and landscaping, without the need to spend too much effort to write the same external code and add different prefixes, but also reduce redundant code.

How to use:

cnpm install --save-dev autoprefixer postcss-loader

var autoprefixer = require(‘autoprefixer‘);module.exports={  //其他配置这里就不写了 module:{ loaders:[ { test:/\.css$/, //在原有基础上加上一个postcss的loader就可以了 loaders:[‘style-loader‘,‘css-loader‘,‘postcss-loader‘] } ] }, postcss:[autoprefixer({browsers:[‘last 2 versions‘]})]}
2. Automatically generate HTML plugins

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() ] }

Function: It will automatically generate a index.html in the Dist directory

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

Additional configuration parameters:

{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 "]}, Span class= "Hljs-attribute" >xhtml:false})]}       
---header.html---<! DOCTYPE html><html> <head> <meta http-equiv=" Content-type "content=" text/html; Charset=utf-8 "/> <title><< Span class= "Hljs-title" >%= htmlwebpackplugin.options.title%> </title> </ head> <body> </body></ HTML>             

Role:

  title: 设置title的名字     filename: 设置这个html的文件名     template:要使用的模块的路径    ‘body‘,     favicon: 给html添加一个favicon  ‘./images/favico.ico‘,     minify:是否压缩  {...} | false (最新api变动,原来是ture|false 感谢@onmi指正)  hash:是否hash化 true false , cache:是否缓存, showErrors:是否显示错误, chunks:目前没太明白 xhtml:是否自动毕业标签 默认false 
3. Extract the style plug-in

Extract-text-webpack-plugin

The official website explains this Extract text from bundle into a file. , adding additional data to the compiled file.

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") ]}

Description: Put CSS on the body of index.html

4. Copy the Resource plugin

Copy-webpack-plugin

The official explanation Copy files and directories in webpack is that copying files and folders in Webpack

install --save-dev copy-webpack-pluginnew CopyWebpackPlugin([{    from: __dirname + ‘/src/public‘}]),

Role: Copy all content in public to the compiled directory

Parameters function Other Notes
From Define the source directory to be copied From: __dirname + '/src/public '
To Define the target directory to bake the chamber From: __dirname + '/dist '
ToType fileOrdir Optional, default is file
Force Force overwrite of previous plugin Optional default False
Context Do not know the role Optional default base context available specific context
Flatten Copy only files regardless of folder Default is False
Ignore Ignore copy of specified file You can use fuzzy matching
5. Global Mount Plugin

Webpack. Provideplugin [Webpack built-in plugin]

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‘)

Function: Corresponds to the above 5 one by one

  当模块使用这些变量的时候,wepback会自动加载。(区别于window挂载,感谢@lihuanghe121指正)  不显示错误插件  查找相等或近似的模块,避免在最终生成的文件中出现重复的模块  丑化js 混淆代码而用  提取公共代码的插件
Second, a complete chestnut
' Use strict ';Modulesvar 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 =functionMakewebpackconfig() {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 '; }Elseif (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 + new webpack. Provideplugin ({$:  "jquery", jquery:  "jquery", " window.jquery ": " JQuery "})} Config.devserver = {contentbase: /src/public ', stats:  ' minimal '}; return config;} ();
Three, debugging skills
if (isTest) {    config.devtool = ‘inline-source-map‘;} 

Function: Using Source-map can see the source code when debugging, convenient to check the wrong

Webpack Advanced Plug-in chapter

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.