Step by step teach you how to use webpack to build a vue scaffold (ultra-detailed explanation and comment), webpackvue

Source: Internet
Author: User
Tags html comment npm scripts postcss

Step by step teach you how to use webpack to build a vue scaffold (ultra-detailed explanation and comment), webpackvue

As one of the three front-end frameworks, Vue has gained 44,873 stars on github so far, which shows that it has quietly become the mainstream. In October, Vue released 2. after a period of exploration and reading official tutorials and APIs, I learned that version 2.0 has made many adjustments based on Version 1.0, and many APIs have been discarded.

This article will introduce in detail the content about using webpack to build a vue scaffold, and share it for your reference and learning. I will not talk about it much below. Let's take a look at the detailed introduction.

1. Applicable groups

1. Those who have some knowledge about webpack but are not familiar with it.

2. Female students !!! (233333 ....)

Ii. Purpose

I want to know more about webpack and help some people who are new to webpack.

Scaffolding has been put on github. If you don't want to hear me, you can download or clone it directly.

Detailed comments are provided in the scaffold!

Source code: https://github.com/webfansplz/xc-cli.git (local download)

I think it is a kind of support for me to help your classmates give me a star!

Iii. Scaffolding Structure
── Build service and webpack Configuration | -- build. js webpack Package Service | -- webpack. base. conf. basic General configurations of js webpack | -- webpack. dev. conf. js webpack Development Environment Configuration | -- webpack. prod. conf. js webpack production environment configuration ── config build different project environment configuration ── public project package file storage directory ── index.html project entry file ── package. json project configuration file ── static resource ──. babelrc babel configuration file ├ ──. gitignore git ignores the file metadata ── postcss. config. js postcss configuration file ├ ── src project directory | -- page component directory | -- router vue route Configuration | -- store vuex Configuration | -- App. vue instance portal | -- main. js project construction Portal
4. Configure npm scripts4.1 to generate the package. json file and configure npm scripts.

4.1.1 use the npm init command to generate a package. json file!

npm init

4.1.2 install webpack and webpack-dev-server globally

npm install webpack webpack-dev-server -g

4.1.3 install webpack and webpack-dev-server in the project directory

npm install webpack webpack-dev-server -D

4.1.4 go to package. json to configure the npm scripts command

 "scripts": { "dev": "webpack-dev-server --config build/webpack.dev.conf.js", "start": "npm run dev", "build": "node build/build.js" }

Configure the preceding command:

We can use npm start/npm run dev for local development,

Explanation of the scripts. dev command:

Use the webpack-dev-server command to start webpack. dev. conf. js in the build folder.

You can also package the project file through npm run build for online deployment.

Explanation of the scripts. build command:

Use the node command to build. js under the build folder.

You can modify the command configuration according to the configuration file location and name of Your scaffold!

5. Build a scaffold directory

Students can build their own directory of scaffolding through their habits and preferences. The following describes the structure of scaffolding above!

6. Build config/config. js

6.1 this file is mainly used to configure differentiated parameters for the development and production environments.

6.2

Const _ path = require ("path"); const ExtractTextPlugin = require ("extract-text-webpack-plugin "); // vue-loader basic configuration const baseVueLoaderConf = {// introduce the postcss plug-in postcss: {config: {path: _ path. resolve (".. /") }}, // convert to require call, so that webpack can process the target resource! TransformToRequire: {video: "src", source: "src", img: "src", image: "xlink: href "}}; // configure const devVueLoaderConf = Object in the vue-loader development environment. assign ({}, baseVueLoaderConf, {// loaders: {css: ["vue-style-loader", "css-loader"], less: ["vue-style-loader", "css-loader", "postcss-loader", "less-loader"]}, cssSourceMap: true }); // configure const buildVueLoaderConf = Object in the vue-loader production environment. assign ({}, baseVue LoaderConf, {// loaders: ExtractTextPlugin. extract ({use: ["css-loader", "postcss-loader", "less-loader"], fallback: "vue-style-loader"}), cssSourceMap: false}); // development/production environment configuration parameters! Module. exports = {dev: {publicPath: "/", devtoolType: "cheap-module-eval-source-map", vueloaderConf: devVueLoaderConf, host: "localhost", port: "1234", proxyTable :{}}, build: {publicPath: "/", devtoolType: "source-map", vueloaderConf: buildVueLoaderConf, staticPath: "static "}};
7. build/webpack. base. conf. js

7.1 this file is mainly used for general configurations of the webpack development environment and generation environment.

7.2

"Use strict"; // introduce the node path module const path = require ("path"); // introduce the webpack production environment Configuration Parameter const prodConfig = require (".. /config "). build; // The splicing path function resolve (track) {return path. join (_ dirname ,".. ", track);} // resource path function assetsPath (_ path) {return path. join (prodConfig. staticPath, _ path);} // webpack Basic settings module. exports = {// project portal file-> webpack is built here! Entry: path. resolve (_ dirname ,".. /src/main. js "), // how the configuration module is parsed resolve: {// automatically parses the file extension (completed file suffix) (from left to right) // import hello from '. /hello '(! Hello. js? ->! Hello. vue? ->! Hello. json) extensions :[". js ",". vue ",". json "], // configure the alias ing alias: {// import Vue from 'vue/dist/vue. esm. js' can be written as import Vue from 'vue '// Add $ after the key, indicating exact match! Vue $: "vue/dist/vue. esm. js "," @ ": resolve (" src "), utils: resolve (" src/utils "), components: resolve (" src/components "), public: resolve ("public") }}, module: {// rules of the processing module (you can use different loaders to process modules here !) Rules: [// use babel-loader to process all js files under src. The specific babel configuration is in. babelrc is mainly used to escape es6 {test :/\. js $/, use: {loader: "babel-loader"}, include: resolve ("src ")}, // use url-loader (A reencapsulation of file-loader) to encode the imported image. Here, you can convert an image smaller than 8192 bytes (8 KB) to DataURL (base64 ), // if it is larger than the limit byte, file-loader will be called for processing! // Images are generally long cached after being published. Therefore, the file name is added to hash for version differentiation! {Test:/\. (png | jpe? G | gif | svg )(\?. *)? $/, Loader: "url-loader", options: {limit: 8192, name: assetsPath ("img/[name]. [hash: 8]. [ext] ") }}]};
8. build/webpack. dev. conf. js

8.1 This file is mainly used to build a development environment.

8.2

"Use strict"; // introduce the node path module const path = require ("path"); // introduce webpackconst webpack = require ("webpack "); // introduce the webpack Development Environment Configuration Parameter const devConfig = require (".. /config "). dev; // introduce the basic webpack configuration const baseConf = require (". /webpack. base. conf "); // A webpack configuration merging module, which can be simply understood as an Object. the assign () function is similar! Const merge = require ("webpack-merge"); // A webpack plug-in that creates an html entry file! Const HtmlWebpackPlugin = require ("html-webpack-plugin"); // A webpack plug-in with compilation prompts! Const FriendlyErrorsPlugin = require ("friendly-errors-webpack-plugin"); // a node module that sends system notifications! Const notifier = require ("node-notifier"); // combine the basic webpack configuration with the development environment configuration! Const devConf = merge (baseConf, {// project exit, the package generated by webpack-dev-server is not written to the hard disk, but stored in the memory! Output: {// file name filename: "[name]. js", // reference the resource path in html. In dev-server, the file in memory is referenced! PublicPath: devConfig. publicPath}, // generate sourceMaps (easy to debug) devtool: devConfig. devtoolType, /// start an express server so that we can develop it locally !!! DevServer: {// HMR console log Level clientLogLevel: "warning", // hot loading hot: true, // automatically refresh inline: true, // open the browser automatically open: true, // It is very useful when developing a single page application. It depends on HTML5 history api. if it is set to true, all features are directed to index.html historyApiFallback: true, // host: devConfig. host, // port: devConfig. port, // configure the reverse proxy to resolve the cross-origin proxy: devConfig. proxyTable, // compress your code. The function of speeding up the development process and optimization is compress: true, // The compiled errors or warnings is displayed in full screen on the browser. Overlay: {errors: true, warnings: false}, // The terminal outputs only the initial startup information. Webpack warnings and errors are not output to the quiet: true} of the terminal, module: {// rules of the processing module (you can use different loaders to process the module here !) Rules: [// use vue-loader to process files ending with vue! {Test: //. vue $/, loader: "vue-loader", options: devConfig. vueloaderConf}, // use vue-style-loader! Css-loader! Postcss-loader processes files ending with css! {Test :/\. css $/, use: ["vue-style-loader", {loader: "css-loader", options: {sourceMap: true },{ loader: "postcss-loader", options: {sourceMap: true}]}, // use vue-style-loader! Css-loader! Postcss-loader processes files ending with less! {Test :/\. less $/, use: ["vue-style-loader", {loader: "css-loader", options: {sourceMap: true },{ loader: "less-loader", options: {sourceMap: true }}, {loader: "postcss-loader", options: {sourceMap: true}]}, plugins: [// enable HMR (the hot replacement function replaces the updated part and does not reload the page !) New webpack. HotModuleReplacementPlugin (), // display the module relative path new webpack. NamedModulesPlugin (), // when an error occurs during compilation, this plug-in can skip the output to ensure that the output resources do not contain errors! // New webpack. NoEmitOnErrorsPlugin (), // configure the html entry information new HtmlWebpackPlugin ({title: "hello, xc-cli! ", Filename:" index.html ", template:" index.html ", // js resource Insertion Location." true "indicates insertion into the inject: true} at the bottom of the body element }), // The compilation prompt plug-in new FriendlyErrorsPlugin ({// The compilation success prompt! CompilationSuccessInfo: {messages: ['your application is running here: http: // $ {devConfig. host }:$ {devConfig. port} ']}, // compilation error! OnErrors: function (severity, errors) {if (severity! = "Error") {return;} const error = errors [0]; const filename = error. file. split ("! "). Pop (); // when a compilation error occurs, an error message is displayed in the lower right corner! Notifier. policy ({title: "xc-cli", message: severity + ":" + error. name, subtitle: filename | "", icon: path. join (_ dirname, "xc-cli.png")}) ;}})]}; module. exports = devConf;

8.3 By creating the above files and downloading the corresponding dependencies and Project Creation portals, we can use npm run dev to develop a vue project locally !!!

9. Create build/webpack. prod. conf. js

9.1 This file is mainly used to build the production environment configuration.

9.2

"Use strict"; // introduce the node path module const path = require ("path"); // introduce webpackconst webpack = require ("webpack "); // A webpack configuration merging module, which can be simply understood as an Object. the assign () function is similar! Const merge = require ("webpack-merge"); // introduce the configuration parameter const prodConfig = require (".. /config "). build; // introduce the basic webpack configuration const baseConf = require (". /webpack. base. conf "); // A webpack plug-in that creates an html entry file! Const HtmlWebpackPlugin = require ("html-webpack-plugin"); // A webpack plug-in that extracts css! Const ExtractTextPlugin = require ("extract-text-webpack-plugin"); // A webpack plug-in for compressing css! Const OptimizeCSSPlugin = require ("optimize-css-assets-webpack-plugin"); // A webpack plugin for copying files! Const CopyWebpackPlugin = require ("copy-webpack-plugin"); // resource path function assetsPath (_ path) {return path. join (prodConfig. staticPath, _ path);} // combines the basic webpack configuration with the production environment configuration! Const prodConf = merge (baseConf, {// configure output: {// path for storing all files after Build. resolve (_ dirname ,".. /public "), // reference the resource path in html. You can configure the cdn reference address here! PublicPath: prodConfig. publicPath, // file name filename: assetsPath ("js/[name]. [chunkhash]. js "), // used to package require. chunkFilename: assetsPath ("js/[name]. [chunkhash]. js ")}, // generate sourceMaps (easy to debug) devtool: prodConfig. devtoolType, module: {// rules of the processing module (you can use different loaders to process the module here !) Rules: [// use vue-loader to process files ending with vue! {Test :/\. vue $/, loader: "vue-loader", options: prodConfig. vueloaderConf}, {test :/\. css $/, use: ExtractTextPlugin. extract ({use: ["css-loader", "postcss-loader"], fallback: "vue-style-loader"}) },{ test :/\. less $/, use: ExtractTextPlugin. extract ({use: ["css-loader", "less-loader", "postcss-loader"], fallback: "vue-style-loader"})}]}, plugins: [// Add hey, xc-cli to each chunk header! New webpack. bannerPlugin ("hey, xc-cli"), // compress js new webpack. optimize. uglifyJsPlugin ({parallel: true, compress: {warnings: false}), // separates the css referenced by the entry and is not embedded in the js bundle! New ExtractTextPlugin ({filename: assetsPath ("css/[name).[contenthash#.css"), allChunks: false}), // compress css new OptimizeCSSPlugin (), // generate a four-digit hash value based on the relative path of the module as the module id new webpack. hashedModuleIdsPlugin (), // improves the scope and speed of code execution in the browser. new webpack. optimize. moduleConcatenationPlugin (), // extract from the public module and synthesize a chunk. The chunk will be cached and used to increase the speed! // 1. Third-party library chunk new webpack. optimize. CommonsChunkPlugin ({name: "vendor", minChunks: function (module) {// js file in node_modules! Return (module. resource & amp &&/\. js $ /. test (module. resource) & module. resource. indexOf (path. join (_ dirname ,".. /node_modules ") === 0) ;}}, // 2. cache chunk new webpack. optimize. commonsChunkPlugin ({name: "manifest", minChunks: Infinity}), // 3. asynchronous public chunk new webpack. optimize. commonsChunkPlugin ({name: "app", children: true, // (select all chunks of the selected chunks) async: true, // (create an asynchronous public chunk) minChunks: 3 // (at least three chunks need to share this module before extraction)}), // copy the entire file to the new CopyWebpackPlugin ([{from: path. resolve (_ dirname ,".. /static "), to: prodConfig. staticPath, ignore :[". * "]}]), // generate html new HtmlWebpackPlugin ({filename: path. resolve (_ dirname ,".. /public/index.html "), template:" index.html ", favicon: path. resolve (_ dirname ,".. /favicon. ico "), // js resource Insertion Location." true "indicates inject: true at the bottom of the body element. // compress the configuration minify: {// Delete the Html comment removeComments: true, // remove space collapseWhitespace: true, // remove attribute quotation marks removeAttributeQuotes: true}, // introduce chunk chunksSortMode: "dependency"})]}); module. exports = prodConf;
10. Create build/build. js

10.1 this file is a project packaging service used to build a full compressed package

10.2

"Use strict"; // node for loadingconst ora = require ("ora"); // rm-rf for nodeconst rm = require ("rimraf "); // console for nodeconst chalk = require ("chalk"); // path for nodeconst path = require ("path"); // webpackconst webpack = require ("webpack "); // webpack production settingconst config = require (". /webpack. prod. conf "); // specify the deleted file const rmFile = path. resolve (_ dirname ,".. /public/static "); // build start load Ingconst spinner = ora ("building for production..."); spinner. start (); // build a full compressed package! Rm (rmFile, function (err) {if (err) throw err; webpack (config, function (err, stats) {spinner. stop (); if (err) throw err; process. stdout. write (stats. toString ({colors: true, modules: false, children: false, chunks: false, chunkModules: false}) + "\ n"); if (stats. hasErrors () {console. log (chalk. red ("Build failed with errors. \ n "); process. exit (1);} console. log (chalk. cyan ("Build complete. \ n "); console. log (chalk. yellow ("Tip: built files are meant to be served over an HTTP server. \ n "+" Opening index.html over file: // won't work. \ n "));});});

10.3 after the above files are created, we can use npm run build to package our project files and deploy them online.

11. Success!

Through the above steps, a spa version of vue scaffolding will be finished!

If you do not know the details, leave a message or go to my github to view the details.

Address: https://github.com/webfansplz/xc-cli.git (local download)

Summary

The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.

Related Article

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.