A, WebPack
Webpack has two main features: 1. Modularity 2. 1 will sass/less precompiled CSS language into a browser to identify CSS files more than 2 can be precompiled packaged into a file 3 packaging image/styles/assets/scrips/front end and the commonly used 4 set up development environment open server 5 monitoring file changes, Hot deployment. 6 Convert single file component (*.vue) files into content recognized by the browser
1. Install WebPack:
$NPM I -d webpack webpack- CLI // -d installed in the development environmentCopy the code
WebPack 4.x supports zero configuration (let’s take a look at how WebPack implements packaged deployment)
$NPX webpack // execute the webpack command based on NPX, which is the lookup order for the package deployment: - Find node_modules/.bin - require that we have webpack. CMD file - execute webpack. CMDCopy the code
NPX is installed automatically since nPM5.2.0 (NPX will help you execute binary files in dependency packages)
For example :(before NPX)
NPM I webpack -d // non-global install // If you want to run the webpack command /node_modules/.bin/webpack -vCopy the code
After a NPX
NPM I webpack -d // Install NPX Webpack -vCopy the code
NPX will automatically look for executable files in the current dependency package, and if not, it will look in the PATH. If you still can’t find it, it will install it for you.
2. Webpack custom configuration
Although WebPack supports zero configuration, we define our own base configuration as required in daily development
Create the webpack.config.js file in the root directory:
/* * set our own packaging rules in this file * 1. All rules are written in module.exports={} */ // let path = require('path'); Exports of module. Exports = {// exports of module. Exports of module. 'the. / SRC/index. Js', / / = > output output: {/ / = > output file name of the file filename:' bundle. Min. [r]. Hash js', / / = > output directory "of" absolute path to the path: path.resolve(__dirname, 'dist') } }Copy the code
3. Customize the configuration file name
We can do this in a package.json file in the root directory
//package.json "scripts": { "serve": "webpack-dev-server --config webpack.config.development.js", "build": "Webpack -- config webpack. Config. Development. Js"} / / so we later can be executed directly by yarn or NPM serve/build, convenient a lotCopy the code
4. webpack-dev-server:
Is a tool used to quickly build a local running environment. Simple webpack-dev-server command or configuration command script to run quickly (serve has been configured in 👆3, we can run serve directly later)
The installation
$yarn add webpack-dev-server -d //=> Run the following command to configure webpack-dev-server: webpack-dev-server --config xxx.js DevServer: {port: 3000, //=> Create port for service progress: ContentBase: './build', //=> Specify the directory in which the current service processes resources open: true //=> Automatically open the browser after the compilation is complete}Copy the code
-
$ npm run serve $ yarn serve $ npx webpack-dev-server Copy the code
5. html-webpack-plugin:
Html-webpack-plugin is used to compile HTML files in webPack projects. If you put the HTML files directly in the./ SRC directory, they will not be compiled into production when packaged with Webpack. Since Webpack compiles any file, it needs to be configured first based on the configuration file.
The Webpack plug-in uses three steps: Install > Import > Configure
Npm&yarn installation
$ npm install --save-dev html-webpack-plugin
$ yarn add html-webpack-plugin --dev
Copy the code
Import (and then import at the beginning of webpack.config.js)
let HtmlWebpackPlugin = require('html-webpack-plugin');
Copy the code
configuration
module.exports = { ... [// new HtmlWebpackPlugin({//=> specify your own template: './ SRC /index.html', //=> the output filename filename: 'index.html', //=> set the HASH stamp to the imported file (clear the cache), or set filename in output: 'bundle. [hash]. Js to generate different file hash: true, / / = > control whether and in what way to minimize the output / / = > HTTP: / / https://github.com/kangax/html-minifier / / control compression minify: { collapseWhitespace: true, removeComments: true, removeAttributeQuotes: true, removeEmptyAttributes: true } }) ] }Copy the code
6. Use loader processing rules (processing styles)
Website: www.webpackjs.com/api/loaders…
The installation
$yarn add css-loader style-loader less less-loader autoprefixer postcss-loader (etc.) -dCopy the code
configuration
Module. exports = {//=> export module: {//=> module rules: [{test: / \. (CSS | less) $/, / / = > based on regular expression matching which modules need to handle the use: ["style-loader", //=> Insert CSS into HEAD "css-loader", //=> compile parse @import/URL() this syntax "postcss-loader", //=> set prefix {loader: "Less - loader", the options: {/ / = > loader additional configuration}}}}}]]Copy the code
In the postcss.config.js file
Module. exports = {plugins: [require('autoprefixer')]};Copy the code
Add at the end of the package.json file
// Like these "> 1%", "last 2 versions" is the query parameter "browserslist": ["> 1%", "last 2 versions"]Copy the code
7. Mini-css-extract-plugin to extract content from CSS (isolate and compress the CSS separately)
The installation
$ yarn add mini-css-extract-plugin optimize-css-assets-webpack-plugin uglifyjs-webpack-plugin -D
Copy the code
The introduction of
let MiniCssExtractPlugin = require('mini-css-extract-plugin'),
OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin'),
UglifyjsWebpackPlugin = require('uglifyjs-webpack-plugin');
Copy the code
configuration
Module. exports = {//=> set optimization: {//=> set minimizer: [/ / CSS = > compression (compression way but must specify the JS) new OptimizeCssAssetsWebpackPlugin (), / / = > compression JS new UglifyjsWebpackPlugin ({cache: Parallel: true, //=> parallel: true, //=> parallel: true, //=> parallel: true, //=> Parallel: true, //=> Parallel: true, //=> Parallel: true, //=> Parallel: true, //=> Parallel: true [//=> new MiniCssExtractPlugin({//=> set filename: 'main.css'})], module: {rules: [{test: /\.(css|less)$/, use: [/ / "style - loader", / / = > MiniCssExtractPlugin loader in the plug-in is used instead of style way. The loader, "CSS - loader", "postcss - loader", "less-loader" ] }] } }Copy the code
8. ES6 conversion and ESLint syntax detection based on Babel
(When we need to deal with some syntax in ES6)
The installation
$ yarn add babel-loader @babel/core @babel/preset-env @babel/plugin-proposal-class-properties @babel/plugin-proposal-decorators @babel/plugin-transform-runtime -D
$ yarn add @babel/runtime @babel/polyfill
$ yarn add eslint eslint-loader -D
Copy the code
configuration
module.exports = { ... , module: {rules: [...,{test: /\.js$/, use: [{loader: 'babel-loader', options: {//=> presets for conversion (ES6->ES5) : ["@babel/ preset-env"], //=> Plugins for ES6/ES7 CLASS based on plugins: [["@babel/plugin-proposal-decorators", {" Legacy ": true }], ["@babel/plugin-proposal-class-properties", { "loose": }], "@babel/plugin-transform-runtime"]}}], //=>, "eslint-loader" //=> set the file to be ignored during compilation and specify the compile directory include: path.resolve(__dirname, 'src'), exclude: /node_modules/ }] } }Copy the code
9. Expose the global Loader
(If you want to use jQuery or $)
The installation
$ yarn add expose-loader -D
Copy the code
configuration
//=> import jquery from 'expose-loader? $! jquery'; $test: require. Resolve ('jquery'), use: $test: require. Resolve ('jquery') ['expose-loader?$'] } let webpack = require('webpack'); Module. exports = {plugins: [//=> insert $new webpack.provideplugin ({'$': 'jquery'})],} //=> insert console.log($); // So that no error is reportedCopy the code
10. Image processing and sub-directory distribution in WebPack
(When we create img in JS, CSS to set the image and the image in HTML page, can be compressed based on this method)
The installation
$ yarn add file-loader url-loader html-withimg-loader -D
Copy the code
configuration
module.exports = { ... Module: {/ / = > module rules: use loader (default) from right to left rules: [..., {/ / there are a lot of image format... test: / \. (PNG | JPG | GIF) $/ I, use: [{//=> Put the size of the image inside the BASE64 loader: 'url-loader', options: {limit: // outputPath:'/images'// outputPath:'/images' Path.resolve (__dirname, 'SRC '), exclude: /node_modules/}, {//=> handle IMG image import in HTML file test: /\.html$/, use: ['html-withimg-loader'] }] } }Copy the code
11. Release files by directory
Module. exports = {output: {//=> plugins: [new MiniCssExtractPlugin({filename: 'the CSS/main CSS'})], the module: {/ / = > module rules: use the loader (default) from right to left rules: [... {test: / \. (PNG | JPG | GIF) $/ I, use: [{options: { outputPath: 'images' } }] }] } }Copy the code
At this point the various webPack configurations are ready for daily development
Vue – Cli scaffold
Before I wrote this ARTICLE, I just knew I could use vue-CLI to directly generate the schema for a Vue project — I didn’t understand how exactly would he deploy
1. What is the CLI
2. Install
NPM install -g@vue /cli //-g global # OR yarn global add @vue/cli // Install based on YARN (yarn needs to be installed)Copy the code
3. Create a vue-cli project
$vue create [project name](follow the NPM package name specification: digits or lowercase)Copy the code
You will be prompted to select a preset. You can choose the default preset that contains the basic Babel + ESLint Settings, or select “Manually selected Features” to select the desired features.
Select the second Manually select features
You can configure your own arrow keys ↑↓ You can select the space bar to confirm that in addition to the two default options, I also select Router, Vuex, CSS pre-processore (according to your own requirements, you can also add later)
Wait for the installation, and the project is basically created
Then you’ll see the project you’ve created open the hello– Xiaokai file in your editor
You can open up the terminal of your editor and I’m using VScode CTRL + ‘and type
$npm run serve 或者 $yarn serve
Copy the code
You are ready to preview the project
4. Compile and package
In production mode, the written content is compiled, packaged, and finally deployed to the server
$npm run build or $yarn build
Copy the code
– Webpack full version
Exports ={} */ let path = require('path'); let HtmlWebpackPlugin = require('html-webpack-plugin'); let MiniCssExtractPlugin = require('mini-css-extract-plugin'), / / to separate CSS separate OptimizeCssAssetsWebpackPlugin = the require (' optimize - CSS - assets - webpack - plugin '), // compressing CSS UglifyjsWebpackPlugin = require('uglifyjs-webpack-plugin'); Let webpack = require('webpack'); New HtmlWebpackPlugin({}); Module. exports = {// configure optimization rule optimization: {// set minimizer: [// Compressing CSS (problem: JS compression is no longer performing its default compression mode, but also using this plugin, which makes it incompressible. So you have to configure the compression of JS) new OptimizeCssAssetsWebpackPlugin (), / / compression JS new UglifyjsWebpackPlugin ({cache: true, / / whether parallel cache usage: SourceMap: true, // start source mapping (easy debugging)})]}, // configure environment development environment production environment (default) mode: 'production', // @babel6 entry: ['@babel/polyfill', './ SRC/index.my.js '], // output: {// output filename //bundle.min.[hash].js make every generated filename hash with a hash value filename: 'bundle.min.js', // filename: 'bundle.min.[hash].js', // The output directory must be the absolute path, __dirName current directory path: path.resolve(__dirName, 'dist'), publicPath: // to configure webpack-dev-server, run the following command: webpack-dev-server --config xxx.js When the service is started, it is not closed by default. When we modify the source file in VScode, it will compile automatically and refresh the browser. Similar to the Live Server plug-in in VScode, it will refresh automatically. 3000, // display the progress of the package compilation progress: true, // specify the directory where the service is processing resources contentBase: './dist', // automatically open the browser when the compilation is complete: [new HtmlWebpackPlugin({// do not specify a template to create an HTML page that follows the default template. './ SRC /index.html', // output filename: 'index.html', // let's introduce the hash stamp after the js file (clear the cache), but in real projects we usually introduce hash to different JS files every time we compile them: True, // control collapse minify: {collapseWhitespace: true, removeComments: true, removeAttributeQuotes: True, removeEmptyAttributes: true}}), new MiniCssExtractPlugin({// specify the output filename: 'main.min.css'}), // inject $new webpack.provideplugin ({'$': 'jquery'}),], // use the loader to process the module: {rules: [{/ / which files based on regular matching processing test: / \. (CSS | less) $/, / / use which loader, control the use of loader (one order: from right to left) use: [/ / "style - loader", / / the compiled in the CSS is inserted into the head of the page (embedded) MiniCssExtractPlugin. Loader, / / loader in the plug-in is used instead of "CSS - loader" style way, // Compile and parse @import/URL() syntax // "postcss-loader",// set the prefix of the loader {loader: "postcss-loader", options: {ident: 'postcss', plugins: [require('autoprefixer')]}}, {loader: "less-loader", // compile less options: {// load additional configuration}}]}, {test: /\.js$/, // handle the loader to compile JS use: [{loader: 'babel-loader', options: {// presets for the conversion (ES6->ES5) : ["@babel/preset-env"], //=> processes the special syntax plugins for classes in ES6/ES7 based on plugins: [ ["@babel/plugin-proposal-decorators", { "legacy": True // handle decorators}], ["@babel/plugin-proposal-class-properties", {"loose": }], "@babel/plugin-transform-runtime"]}}], "@babel/plugin-transform-runtime"]}}], "@babel/plugin-transform-runtime"]}}], Path.resolve (__dirname, 'SRC '), // compile exclude: /node_modules / \. (PNG | JPG | | GIF jpeg | ico | webp | BPM) $/ I use: [{loader: 'url - loader, the options: {/ / as long as the picture is less than 200 KB, when dealing with direct base64 limit: 2 * 1024, / / control after the packaging images directory outputPath: 'images'}}}, {/ / processing HTML file to import the img file test: / \. (HTML | HTM | XML) $/ I use: ['html-withimg-loader'] }] } }Copy the code