Webpack 4.X from beginner to proficient-entry and output (i)

Source: Internet
Author: User

Review history

WebApplication is increasingly complex, the front-end development has also undergone tremendous changes have become intertwined, to today is very complex and huge! The html era of using, css and javascript Honestly writing a page, is long gone. And now it takes a lot of extra stuff to get the job done, like engineering, automation, and so on. So it appears that there is a force lattice, just like a real program ape. If you still stay in the cut a diagram, download a JS effect godless up the stage, obviously you will be disjointed. This also led to the development of a lot of front-end tools, to Gulp , Grunt , and webpack so on behalf of the building tools like springing up, and webpack more popular, the use of more extensive, it can be said that it is now the front-end development of the standard. So this time I will use a series of articles in detail to introduce webpack , simple analysis webpack , and then through the practical examples of cooperation, Master will be enough to solve your work problems. At the same time this series of articles is 4.X for the latest version.

What is Webpack?

webpackIs it a tool? What tools? Someone called him a packing tool, so it was too low. Can take a look at the Webpack official website, the bottom of the page of a small avatar represents the webpack people who have been sponsored, the mouse can also see how much money he sponsored. With so many people's sponsorship, can not be called so low force name, listen to like a compression software. Can afford a tall name, called the Build tool (of course, the function of packaging is a major feature of it)

What's in front of the engineering AH Automation Ah, these things have a feature, is that the source code can not be directly in the browser to run, must be compiled before the line. That build tool can actually do these things. Such as:

  • Code compilation, turn ES6 into ES5
  • Module merging, merging multiple files into one file, reducing HTTP requests
  • Code compression optimization, extracting common code, reducing the amount of code

These are the things that build tools do, but these things are implemented in code to automate these things through code and liberate our productivity. webpackone of the biggest features is packaging, the official website of the big picture is the packaging of the function, and can solve the problem of inter-module interdependence, it can be messy into porridge files packaged into a clear file, the Gordian Knot! followed by the webapck module as the cornerstone, for the modularity of support embodies the incisively and vividly, in webpack all the content is a module, a picture, a CSS file, a JS file is a module.

Installation
  1. NPM init-y
  2. NPM Install--save-dev Webpack
  3. NPM Install--save-dev WEBPACK-CLI

Attention:
1, the installation before the confirmation of an event, nodejs the version of more than 5.0
2. NPM init-y for generating package.json files
3, two commands can be abbreviated as: NPM i webpack webpack-cli-d
4, it is recommended to install in the project rather than the global environment. Problems with installing to a global environment may cause plugins to be unusable and avoid different versions of project dependencies
5, 4.x The version of the CLI has been separated out, so must be installedwebpack-cli
6. Verify that the installation is successful: Webpack-v

Configuration file

Configuration files like webpack the brain, webpack the work is done through the configuration file. Compile which file, how to compile, compile into what, output why and so on, all the operations are done by the contents of the configuration file, so the configuration file a heavyweight guest, webapck want to run the word configuration file is essential.

The configuration file has 6 core components, just like a JavaScript ECMAScript , three- DOM BOM part composition.

  1. entry: Entry file (you need to pack it and tell me what to pack)
  2. output: Export Documents (I'm finished packing, where to put them)
  3. module: module (Put Lorder, compile what the browser does not know)
  4. plugins: Plug-in (support development, improve development efficiency)
  5. devServer: Server (local server provided by Webpack)
  6. mode: mode, divided into development mode, production mode. This is 4. X in the new

Attention:
1, the name of the configuration file is called webpack.config.js , need to be placed in the root directory of the project folder. Of course you can switch to other names, but you'll need to add extra steps when you're running.
2, the webpack use CommonJS of the specification, all the above parameters need to be placed in the object, with the moudle.exports export

Small trial Sledgehammer

Create the necessary folders and files under the root directory of the project folder (my Webpack-demo), with the following structure:

    • [] Webpack-demo
      • [] node_modules
      • [] src
        • Main.js
        • Show.js
      • [] index.html
      • [] Package.json
      • [] webpack.config.js

Such as

The Show.js code is as follows

//声明一个函数,最终做为一个模块被导出const show=content=>{    const box=document.getElementById("box");    box.innerHTML=`你好!${content}`;}export {show};  //ES6导出模块的语法

The Main.js code is as follows

import {show} from ‘./show‘;    //ES6导入模块的语法,‘./’为main.js的根目录src,ES6里导入的模块为js话不需要加后缀名show(‘kaivon‘);

The index.html code is as follows

<!DOCTYPE html>

The Package.json code is as follows

const path=require(‘path‘); //nodejs的语法,引入路径模块,为了输出的时候找绝对路径module.exports={ entry:‘./src/main.js‘, //入口文件为main.js output:{ //输出 path:path.resolve(__dirname,‘dist‘), //path.resolve为nodejs的固定语法,用于找到当前文件的绝对路径 filename:‘bundle.js‘ //输出的文件名 },};

After executing the command in the terminal webpack , the terminal displays the following, which means it is successful.

Also look at the file structure directory, more than one dist folder, as well as bundle.js files. These are the webpack files that the package generates, as follows

After introducing the file into the index.html file, open it in a bundle.js browser index.html and you can see the contents of the page. This means that we have already used webpack a packaged file, and its basic usage has gone.

<body> <div id="box"></div> <script src="dist/bundle.js"></script></body>
Syntax and procedure syntax
  1. entryEntry file
    • Package only one file (single entry), write a string
    • Package multiple files into one file, write the number of groups
    • Package multiple files into multiple files and write them as objects
    • webpackCall the packaged file.Chunck
  2. outputExport documents
    • filenameThe name of the output file
      1. Output a file, write a string
      2, output multiple files, the file name preceded by an identifier (Id/name/hash)
    • pathPath to output file
      1. Path must be absolute path
      2, __dirname is nodejs a module in, indicating the absolute path of the current file
      3, path for nodejs the system module, directly introduced after the call path.resolve(__dirname,‘输出文件的路径‘) ;
Steps

When we enter a command in the terminal webpack , we webpack begin to work as follows:

  1. Open the root directory first.webpack.config.js
  2. entryvalue to find (Ingress) property
  3. Into the main.js inside, see it and depend show.js , and findshow.js
  4. main.jsCombine and show.js merge into a JS file
  5. webpack.config.jsfind output (export) attribute in
  6. The output path filename value of the attribute in the parse
  7. Put the 4th step into the JS file in the dist folder, and a name calledbundle.js
Strike while

The following demo multi-entry, in the directory of the src new two JS file, 1.js with 2.js , the code is as follows:
1.js

console.log(‘这是第一个入口文件!‘);

2.js

console.log(‘这是第二个入口文件!‘);

Modify a webpack.config.js file

const path=require(‘path‘);//两个entry分别一一对应两个filenamemodule.exports={    //entry:[‘./src/1.js‘,‘./src/2.js‘],    entry:{        one:‘./src/1.js‘,        two:‘./src/2.js‘    },    output:{        //filename:‘bundle.js‘,        filename:‘[name].bundle.js‘ //可以以name/id/hash放在中括号里区分文件名        path:path.resolve(__dirname,‘dist‘),    }}

Separate comments corresponding to entry filename , in the terminal to execute the command: Webpack, after viewing the dist folder and after running to index.html see the effect
1, when an entry webpack array, will be all the files in the arrays into a JS file
2, when the entry object, webpack will be the object of the files are packaged into multiple files

In the article is only entry and output of the common configuration, it is more than these configuration, you can refer to the following links
entryAll configurations of https://webpack.js.org/concepts/entry-points/
outputAll configurations of https://webpack.js.org/concepts/output/

Data download

Webpack 4.X from beginner to proficient-entry and output (i)

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.