Detailed explanation How to pack VUE projects using WebPack

Using WebPack Package Vue Project

For one year, from nothing understand, I don’t understand what I know everything, It is also a leap. Sigh of the current front end, from nodejs, now all kinds of tools, such as the rain, spring. The big gods crazy cranes, and it is not easy to play. I am waiting Xiaobai, crazy chasing, and learning the heart and spleen and blood failure. And my energy is only limited to it, but I have a little more beneficial. This article is to introduce how to build front-end projects using WebPack.

This project is the protagonist as Vue.js, Vue.js is a small and elegant and powerful lightweight MVVM framework, with the WebPack module Capture. Produces the effect as shown below. Just take a frame, you will use a lot of plugins and loaders.

Environmental Preparation 详解如何使用webpack打包Vue工程

Mainly some global nodejs bag

nodejs

WebPack
  1. Less
  2. sudo npm install weight webpack -g // -g represents global installation WebPack, The command line can be used to use the webpack command sudo npm install less -g // -g globally installed the LESS TO CSS converter
start
  1. Initialization Engine  
Create a project folder New and positioned to new

MKDIR New && CD New

NPM initialization project
NPM INIT
   
As needed, the item is set, or All the way, use the default information, the default item name is the folder name (the project name does not set to a module name, otherwise you will report an error when you quote the module in the future)

Name: (NEW): (1.0.0) Description: entry point: (index.js) Test Command: Git repository: keywords: newauthor: fzlicense: (ISC) {“Name”: “gt”, ” “1.0.0”, “description”: “”, “main”: “index.js”, “scripts”: {“test”: “echo \” error: no test specified \ “&& exit 1” }, “keywords”: [“new”, “author”: “fz”, “license”: “ISC”} IS this ok? (yes)
   
After the folder, a package.json will generate a detailed information of the project, including various dependent and plugins.
2. Create a directory and WebPack configuration file

├── Directory for output file after Dist // – SRC // Application logic code Storage area │ ├── LIB // Store NPM Third Party Library │ │ ├─Backbone.js│ │ └── Underscore.js│ ├── static // Static Resource │ │ └─Logo.png│ ├── APP.HTML / / Parts Template │ ├─ APP.JS / / Parts Code │ └─App.less // Parts Style ├─ ─ ─ ─ ─── ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ WebPack.config .js // WebPack configuration file
   
The current directory structure, the file is blank, and then makes them up. 3. Install the loader (loader) and plugins of the module of WebPack and the module we need

NPM INSTALL –SAVE LESS // Local Press the loader of the Lessnpm Install – Save Less-loader // LESS module, with the following Css-Loader and Style-Loadernpm Install – Save CSS-Loader // CSS Module Adder NPM Install –Save Style-Loader // The base NPM Install – Save Url-loader // of the above two plugins is used to process the image font, which is encapsulated by the following File-Loader. Custom file name NPM install –save file-loader npm install –save html-loader // Loading HTML file NPM Install – Save Text-loader //Loading plain text NPM Install – Save HTML-WebPack-Plugin // Generate HTML File Plugin NPM Install –Save Extract-Text-WebPack-Plugin // Extracts CSS File Plugin NPM Install – Save WebPack // Provides WebPack Object NPM Install – Save WebPack-Dev-Server // WebPack-Server Development Pack, easy to debug NPM Install –save Vuenpm Install –Save jQuery
   4. Completion The post-package.json 
{“Name”: “New”, “Version”: “1.0.0”, “Description”: “,” main “: “index.js”, “scripts”: {“dev”: “WebPack-Dev-Server –hot –NLine”, // User Launches WebPack-Dev-Server is used for user debugging – the head represents hot replacement, – -inline mode. . not sure. “TEST”: “echo \” error: no test specified \ “&& exit 1”}, “keywords”: [“new”, “author”: “FZ”, “license”: “ISC”, “dependencies” : {“Bootstrap”: “^ 3.3.6”, “CSS-Loader”: “^ 0.23.1”, “Extract-text-WebPack-Plugin “:” ^ 1.0.1 “,” File-loader “:” ^ 0.9.0 “,” HTML-Loader “:” ^ 0.4.3 “,” HTML-WebPack-Plugin “:” ^ 2.22. 0 “,” jQuery “:” ^ 2.1.4 “,” LESS “:” ^ 2.7.1 “,” Less-loader “:” ^ 2.2.3 “,” Style-loader “:” ^ 0.13.1 ” “TEXT-Loader”: “0.0.1”, “URL-Loader”: “^ 0.5.7”, “Vue”: “^ 1.0.26”, “Webpack”: “^ 1.13.1”, “WebPack -dev-server “:” ^ 1.14.1 “}

3. Written WebPack.Config.js Profile

The WebPack configuration file is more complicated, you need to do this: WebPack as a module package, its management unit is the module, the webpack module refers to not just JS, including style, pictures, fonts, templates, etc. The module needs to be loaded as the loader as the loader.
   
VAR WebPack = Require (‘WebPack’); var path = required (‘PATH’); var htmlwebpackplugin = Require (‘HTML-WebPack-Plugin’); Var extractTextWebPackPlugin = Require (‘extract-text-webpack-plugin “);

introduces necessary plugins and modules
  Module.Exports = {Entry: {"INDEX": "./index.js", "common": ['Vue', 'jQuery', 'underscore ",' Backbone ']},  
Entry as the name refers to the entrance, he is the entrance of the program, but it is also a CHUNK (Code block) constructor. There are two ways to construct, one of the above, through the module relationship within the file, and package the file into a CHUNK. One of the other means that this CHUNK is the case (BACKBONE, Underscore, etc.) defined below, Vue, jQuery, can be installed directly through NPM).

This configuration compiles two files, one as a public library, one is used as a website entry.

Output: {path: ‘./dist’, publicPath: ‘/ Path /’, filename: ‘[name]. [Hash] .js’},
  Here is the output file control  
PATH: Output compile file path

PublicPath: in HTML-WebPack -plugin, the root directory of the script is introduced. (Generated)

FileName: Output file name, [Name] means what the name is what the name is called, [hash], file hash value.
  For example: the entrance file name is Index, then its output is index.d87f87sd6fsdgs76gsd967.js  
Module: {loaders: [{test: /\.less! {Test: ‘style-loader! Css-loader! Less- Loader ‘}, {Test: /. (“” style-loader “,” css-loader! less-loader “) // with’ extract-text-webpack-plugin ‘can be peeled off in conjunction with’ extract-text-webpack-plugin ‘ , Css}, {test: /\.css $/, loader: ‘style-loader! Css-loader’}, {test: /\. (PNG|JPG|GIF|Woff|Woff2|tf|Eot|SVG) $ /, loader: ‘url-loader? limited is the threshold 8 megab to convert the base64 file size}, {Test: /\.html /, loader:’ html-loader ‘// can Used to load template}]},


I don’t know very well, I only know that it can be used here for the Loader definition. Loaders is an array.

TEST: Defines the file name regular expression of the load module
 Loader: Defines the loader   
of the loader, the loader can be used in combination, typical is Style CSS LESS, logic is still very clear, LESS turn CSS turning pattern module, then Insert a document.

  1. resolve: {root: [path.resolve (__ dirname, ‘src / lib’)], extensions: [ ”, ‘.js’], alias: { ‘underscore.js’, ‘backbone’: ‘backbone.js’,}},
  2. The module function is parsed to parse the triplet module and some Require Incidential module.
  3. root: Module Search path array, tell WebPack where to find modules. I define a SRC / LIB path here, I put some library under this path. When referenced, you can directly remove (‘understandcore.x.x.js’); no need to add a path.
EXTENSIONS: Once the name, set the extension name, you can require (‘understand “, do not add .js, here must set this, otherwise, WebPack-dev-server will report an error, sincerely pit.

Alias: After the above settings, I have been able to introduce the tripart module as you like, but I feel better, more convenient to manage. Avoid using the path when references the public library in the file, such as require (‘../../ lib / sssss.js’). Define in the alias.

PLUgins: [New WebPack.Optimize.commonschunkplugin ({name: ‘common “, filename:’ [name]. [hash] .js’, chunks: [‘index’, ‘common’] // extract Commonk from Index & Common }), new htmlwebpackplugin ({template: ‘./index.html’, filename: ‘Index.html’, Chunks: [‘Index’, ‘Common’]}, New WebPack.ProvidePlugin ({jQuery: “jQuery” }), new webpack.optimize.uglifyjsplugin (), new extractTextWebPackPlugin (“style.css”, {allchunks: true})]};
   
Insert library definition

CommonschunkPlugin This plugin is a plug-in for extracting public modules. It analyzes the modules they use from several chunk blocks in Chunks, and packaged into a Name defined chunk code block, you will find CommON code block and entrance’s CommON code block retrieved, we can rewrite a new name. You can also write. If the rename, the module in the generated common.js is all modules defined by the Entry entry. [‘Vue’, ‘jQuery’, ‘underscore’, ‘backbone’], this is also moreHard understanding because we.

    The HTMLWebPackPlugin plug-in is not a web that comes with the webpack. Its role is based on the CHUNK code block generation document, the following means introducing index.js code and common.js code in Index.html.
  1. WebPack.ProvidePlugin plug-in for some libraries, such as bootstrap, package no error, but put on the browser, because Bootstrap is incorporated in the global jQuery variable, WebPack Each module is independent. JQuery is also, jQuery cannot assign a value to Window, causing an error, this plugin, is sent to the jQuery module to the global jQuery variable. Bootstrap no longer reports

  2. ExtractTextWebPackPlugin This external plugin can be peeled out separately and save it as a separate style file.

The plugin can be more developed, because the plug-ins, the slower the compilation, we don’t need so many plugins when developing the environment, the production environment is only needed, so You can do some processing, dynamically add a plugin. There is an article here to do, not introduced.

4. Write logic code
   // index.jsvar Vue = Require ('Vue'); var app = new Vue ({EL: ' #app ', Components: {app: Require (' ./ src / app.js')}}); 

Require (‘Vue’), using the VUE module New Vue instance, (Vue specific to the official website), built an app word component, get the synchronous method, under ./src/ directoryApp.js module.

    // Index.html entry template
  1. VueApp
   
HTML-WebPack-Plugin automatically generates inserted script to make an inlet.

// app.jsvar template = Require (‘./ app.html’); request (‘./ app.less “; module.exports = {TEMPLATE : Template, Data: Function () {Return {Message: ‘Hello Word !!’;}};
  1. /// App.html View Template

/ / app.less view style # div1 {text-align: center;} # Div2 {font-size: 30px;}

Define a view, as a home page, introduced template Introduce the style, a spa shelf is so good.
 5. Compilation   Command line input in the engineering directory 
Webpack

    ├── DIST│ ├─ Common.6b92c6b075a69a71d22f.js│ ├─ ─ ─ 中.6b92c6b075a69a71d22f.js│ ├─ index.html│ └ --- style.6b92c6b075a69a71d22f.css    Compilation completion, you can see the above directory, Common is public extracted Module, Style is a public extracted CSS file, Index.js, logical entry. The project package is completed.   6. Debugging and development    WebPack provides a WEPPACK-Dev-Server plugin, which is convenient for us to debug, we define a command in the script of package.json:    'DEV': 'Webpack-Dev-Server --hot --Nline' 

We can Enter NPM Run DEV in the command line, enter the page in the browser. You can see the webpage.
 The above is all the content of this article, I hope to help everyone, I hope everyone will support Tumi Clouds.                      
© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment