Tag: Sync Core Gen View Poll file header sharing function
GitHub Source Address Https://github.com/ghshuo/webpack-demo
Webpack Introduction
Webpack is a static module wrapper for a modern JavaScript application (modules bundler). When Webpack processes an application, it constructs a dependency graph (dependency graph) recursively, which contains each module that the application requires, and then packages all of them into one or more bundles.
Learning Documents:
- Webpack Official website: http://webpack.github.io/
- Webpack document (English): https://webpack.js.org/
- Webpack Document (Chinese): https://doc.webpack-china.org/
Installation 1. Global Installation Webpack
npm install webpack -gnpm install [email protected] -g 可以规定webpack的安装版本
2. Initialization
3. Partial installation in the project
npm install webpack --save-dev
Webpack.config.js Configuring 1.entry Options (Ingress configuration)
entry:{entry: ‘./src/entry.js‘,}
2.entry option (Export configuration)
output:{path: path.resolve(__dirname,‘dist‘), // 出口地址 绝对路径filename:‘[name].js‘ // //输出的文件名称}
3.module Module Interpreting CSS
Installation
npm install style-loader --save-devnpm install --save-dev css-loader
Configuration in module modules
module:{rules: [{test: /\.css$/,use: [ ‘style-loader‘, ‘css-loader‘ ]}]},
Configure picture
* npm install --save-dev file-loader url-loader* file-loader 解决引用路径的问题* url-loader 如果图片较多,会发很多http请求,会降低页面性能。
{ // 配置图片test: /\.(png|jpg|gif)/,use:[{loader:‘url-loader‘, // url-loaderoptions:{limit:400000, // 是把小于400000B的文件打成Base64的格式outputPath:‘images/‘ // 把图片打包到指定路径下}}]}
Refer to IMG Images directly in the file
npm install html-withimg-loader --save
{test: /\.(htm|html)$/i,use:[ ‘html-withimg-loader‘] }
4.plugins plug-in compression code
* 引入: 不需要安装 const uglifyJsPlugin = require(‘uglifyjs-webpack-plugin‘);
配置plugins:[new uglifyJsPlugin() ]
HTML packaging
* npm install --save-dev html-webpack-plugin
const htmlPlugin = require(‘html-webpack-plugin‘);plugins:[new htmlPlugin({minify:{removeAttributeQuotes:true // minify:是对html文件进行压缩,removeAttrubuteQuotes是却掉属性的双引号。},hash:true, // 为了开发中js有缓存效果,所以加入hash,这样可以有效避免缓存JS。template:‘./src/index.html‘ //是要打包的html模版路径和文件名称})]
5. Hot Update function
npm install webpack-dev-server --save-dev
Again set
devServer:{//设置基本目录结构contentBase:path.resolve(__dirname,‘dist‘),//服务器的IP地址,可以使用IP也可以使用localhosthost:‘localhost‘,//服务端压缩是否开启compress:true,//配置服务端口号, 可以自己设置端口号port: 1818}
General Direct launch of NPM run server to view hot updates
If you cannot add a Hotmodulereplacementplugin plugin to a hot update
Configuration in Plugins
newwebpack.HotModuleReplacementPlugin()
6.CSS Separation and Image path processing
Extract CSS separately, separate CSS
npm n install --save-dev extract-text-webpack-plugin
const extractTextPlugin = require("extract-text-webpack-plugin");plugins[new extractTextPlugin("/css/index.css")]再配置下模块module:{rules:[{test: /\.css$/,use: extractTextPlugin.extract({fallback: "style-loader",use: "css-loader"})}]}分离出来之后css路径不正确 需要下面修改下var filePath = {publicPath: "http://localhost:1818/" // 声明一个路径 处理静态文件路径}//出口文件的配置项output:{publicPath:website.publicPath}
Installing the CSS Precompiled language 1.less
npm install --save-dev lessnpm install --save-dev less-loader
Webpack.config.js
Configure less
{test:/\.less$/,use: [{loader:"style-loader"},{loader:"css-loader",{loader:"less-loader"}]}
Less separation
NPM N Install--Save-Dev Extract-Text-Webpack-PluginConstExtracttextplugin= require("Extract-text-webpack-plugin");plugins[New Extracttextplugin("/css/index.css")]use:Extracttextplugin.Extract({ Use:[{Loader:' Css-loader '},{Loader:' Less-loader '}],fallback:' Style-loader '})
2.sass
--save-dev node---save-dev sass-loader
{ test : / \. scss $ / use : extracttextplugin . extract ({ use : [{ loader : "Css-loader" }, { loader : } ] fallback : "Style-loader" } ) }
Automatic processing of CSS3 property pre-stamp
Need to install two packages Postcss-loader and autoprefixer (auto add prefix plugin)
npm n install --save-dev postcss-loader autoprefixer
Create a new Postcss.config.js file under the Webpack.config.js sibling directory
module.exports={plugins: [require(‘autoprefixer‘)]}
Loader configuration
{Test: /\.CSS$/, Use: Extracttextplugin.Extract({fallback: ' Style-loader ', Use:[{ Loader: ' Css-loader ', Options: { importloaders: 1 } },' Postcss-loader ']})}
Eliminate unused CSS
Installing Purifycss-webpack
npm i -D purifycss-webpack purify-css
Introduction of Glob
Because we need to check the HTML template synchronously, we need to introduce node's Glob object to use. Introduce glob in the Webpack.config.js file header.
constc glob = require(‘glob‘);
Introduction of PURIFYCSS-WEBAPCK
constc PurifyCSSPlugin = require("purifycss-webpack");
Configure Plugins
newPurifyCSSPlugin({paths:glob.sync(path.join(__dirname,‘src/*.html‘)),})
Babel
Turn Es6 into ES5 grammar
npm i -D babel-loader babel-core babel-preset-env babel-polyfill
Configuration in Module
{test:/\.(jsx|js)$/,use:{loader:‘babel-loader‘,},exclude:/node_modules/}
Configuring Babel Preset Files
Create a. babelrc file under the root directory
{"presets": ["env"]}
Packaging debugging
Source-map: Produces a complete and fully functional file in a separate file. This file has the best source map, but it slows down the packaging speed;
Cheap-module-source-map: Creating a map with no column mappings in a separate file, without column mappings, increases packaging speed, but also makes browser developer tools only correspond to specific rows, not to specific columns (symbols), which can cause inconvenience to debugging.
Eval-source-map: Using the Eval package source file module, in the same file to produce a clean full version of the Sourcemap, but the packaging after the output of the JS file execution has a performance and security implications. This is a very good option during the development phase, and it must not be turned on during the production phase.
Cheap-module-eval-source-map: This is the fastest way to produce a source map when you package a file, and the source map produced will be displayed with the packaged JavaScript file, without a innuendo column, And the EVAL-SOURCE-MAP option have similar drawbacks.
module.exports={devtool:‘eval-source-map‘,}}
Configure production and development parallelism
Modify the Package.json command
is to add a dev setting and differentiate it by environment variables, and here is the value in Package.json.
"scripts":{"server":"webpack-dev-server --open","dev":"set type=dev&webapck","build":"set type=build&webpack"}
Modify the Webpack.config.js file
if(process.env.type=="build"){var={publicPath:"线上地址/"}}else{var={publicPath:"本地地址/"}}
Print the value passed over
console.log( encodeURIComponent(process.env.type) );
Referencing third-party libraries
Installation
npm install --save jquery
Introducing Provideplugin plugins with plugin
constc webpack = require(‘webpack‘);
Plugins configuration in Webpack.config.js
plugins:[new webpack.ProvidePlugin({$:"jquery"})]
Watch usage
As the project is large, we don't need to pack every time when the project is being linked, and watch solves the problem, as long as the code is saved and packaged automatically. Watch is a webpack in the self-contained
watchOptions:{//检测修改的时间,以毫秒为单位poll:1000,//防止重复保存而发生重复编译错误。这里设置的500是半秒内重复保存,不进行打包操作aggregateTimeout:500,//不监听的目录ignored:/node_modules/,}
But to run this plugin you have to introduce Webpack
const=require(‘webpack‘);
Run Webpack--watch for packaging
Add Comment All rights reserved
Bannerplugin Plug-in
JS on the Add Z comment who wrote, creation time, can be set
newwebpack.BannerPlugin(‘hsgeng版权所有‘)
Multiple third-party library extraction
----save jquery
Portal File Configuration
entry:{entry:‘./src/entry.js‘,jquery:‘jquery‘,vue:‘vue‘}
newwebpack.optimize.CommonsChunkPlugin({//name对应入口文件中的名字,我们起的是jQueryname:[‘jquery‘,‘vue‘],//把文件打包到哪里,是一个路径filename:"assets/js/[name].js",//最小打包的文件模块数,这里直接写2就好minChunks:2})
Static resource output
There are some static resources (pictures, development documents) that are not referenced in the project, and you want to keep these static resources when you package them, and you can package them directly under the specified folder.
Installation
--save-dev copy-webpack-plugin
Introduced
const copyWebpackPlugin=require("copy-webpack-plugin");
Plugins for configuration
newcopyWebpackPlugin([{from:__dirname+‘/src/public‘,// 要打包的静态资源目录地址to:‘./public‘// 要打包到的文件夹路径,跟随output配置中的目录}])
The JSON configuration file uses
Referencing JSON in the portal file
var json =require(‘../config.json‘);document.getElementById("json").innerHTML= json.name;
Packaging commands
Webpack
Run
NPM Run Server
Summarize
The process of learning Webpack is summarized. If there is something wrong with the place, please correct me, thank you!
Webpack Learning Summary Demo