First of all, I would like to thank all the friends who have read this article. I am a rookie who loves technology. Writing this article is a summary of the new Version of Webpackage 4.0 that I have seen on a certain class network, which is also counted as a learning record. But if you see a summary of my mistakes please feel free to comment.

What is Webpack?

Webpack is an open source front-end packaging tool.

The history of front-end code

Previous front-end code comparisons

// html <! DOCTYPE HTML > < HTML > <head> <title> My page </title> </head> <body> <div id="root"></div>
</body>
<script type="text/javascript" src="./index.js"></script>
</html>

// index.js
var header =  document.createElement('div');
header.innerText = 'head';
document.body.append(header);

var slider =  document.createElement('div');
slider.innerText = 'slider';
document.body.append(slider);

var footer =  document.createElement('div');
footer.innerText = 'at the bottom of the';
document.body.append(footer);
Copy the code

The three modules on our page are header/sliser/footer

  • There’s a lot of code on the page
  • Problems can not be directly defined to the specific content
  • All js in one file causes the file to be too large

Code splitting process

So we split the code into three separate modules

// index.html <! DOCTYPE HTML > < HTML > <head> <title> My page </title> </head> <body> <div id="root"></div>
</body>
<script type="text/javascript" src="./header.js"></script>
<script type="text/javascript" src="./slider.js"></script>
<script type="text/javascript" src="./footer.js"></script>
<script type="text/javascript" src="./index.js"></script>
</html>

// header.js
function Header(){
	var header =  document.createElement('div');
	header.innerText = 'head';
	document.body.append(header);
}

// slider.js
function Slider(){
	var slider =  document.createElement('div');
	slider.innerText = 'slider';
	document.body.append(slider);
}

// footer.js
function Footer(){
	var footer =  document.createElement('div');
	footer.innerText = 'at the bottom of the';
	document.body.append(footer);
}

// index.js
new Header();
new Slider();
new Footer();
Copy the code

We can quickly summarize the advantages and disadvantages compared to the previous code

  • More modular code
  • The content of the file is greatly reduced
  • Cannot locate a module content directly
  • The number of files has increased significantly and the number of requests for resources has also increased

Hello, I’m Import… from …

As you know, in ES6 we use import to import a module, so we can quickly rewrite the previous code (Es Moudule module introduction).

// index.js
function Header(){
	var header =  document.createElement('div');
	header.innerText = 'head';
	document.body.append(header);
}
export default Header

// silder.js
function Slider(){
	var slider =  document.createElement('div');
	slider.innerText = 'slider';
	document.body.append(slider);
}
export default Slider

// footer.js
function Footer(){
	var footer =  document.createElement('div');
	footer.innerText = 'at the bottom of the';
	document.body.append(footer);
}
export default Footer

// index.js
import Header from './header.js'
import Slider from './slider.js'
import Footer from './footer.js'

new Header()
new Slider()
new Footer()
Copy the code

Hello, I am moudule. Export require

// index.js
var Header = require('./header.js')
var Slider = require('./slider.js')
var Footer = require('./footer.js')

new Header()
new Slider()
new Footer()

// header.js
function Header(){
	var header =  document.createElement('div');
	header.innerText = 'head';
	document.body.append(header);
}
module.exports = Header

// slider.js
function Slider(){
	var slider =  document.createElement('div');
	slider.innerText = 'slider';
	document.body.append(slider);
}
module.exports = Slider

// footer.js
function Footer(){
	var footer =  document.createElement('div');
	footer.innerText = 'at the bottom of the';
	document.body.append(footer);
}

module.exports = Footer
Copy the code

In this case, the code will become module clear, but in the process of running, you will certainly find problems, in the browser is not aware of the import export syntax, we can directly use the following command to deal with node.js, detailed introduction will be explained in the following article.

npx webpack index.js
Copy the code

This will generate a dist package folder with main.js in it. /dist/main.js will run directly in index.html.

So what is NPX?

NPX is a command released after NPM5.2, which I understand is a package executor. He will help you execute the binaries in the dependency package.

So how do we install this Webpack?

Install webpack

Global installation

NPM install -g webpack webpack-cli // cli can help us to run the webpack command correctly in the command lineCopy the code

That way, you can use the Webpack command anywhere in the project, directly after a successful installation

webpack -v
Copy the code

You can view the current version number of Webpack

We strongly recommend not doing this at this point, because if we use Webpack 3.* in one project and Webpack 4.* in another, all projects will follow your global WebPack configuration.

Therefore, we usually install Webpack according to the requirements of the project. For example, the webpack of my project uses 3.0.6, so we can add @ to declare the version number during the installation process.

NPM install [email protected] webpack-cli -d (-- save-dev)Copy the code

Additional knowledge

NPM install moduleName command 1. Install the module to the node_modules directory of the project. 2. Do not write module dependencies to devDependencies or dependencies nodes. 3. The module will not be downloaded when running NPM install to initialize the project. NPM install -g moduleName Installing modules globally does not save module packages in the project node_modules directory. 2. Do not write module dependencies to devDependencies or dependencies nodes. 3. The module will not be downloaded when running NPM install to initialize the project. NPM install -save moduleName 1. Install the module to the project node_modules directory. Write module dependencies to the Dependencies node. 3. When running NPM install to initialize the project, the module will be downloaded to the project directory. 4. If you run NPM install --production or specify NODE_ENV as production, the module will be automatically downloaded to node_modules. NPM install-save-dev moduleName command 1. Install the module to the project node_modules directory. 2. Write module dependencies to the devDependencies node. 3. When running NPM install to initialize the project, the module will be downloaded to the project directory. 4. Running NPM install --production or specifying NODE_ENV as production does not automatically download modules to the node_modules directory.Copy the code

This way, you can use WebPack depending on the specific release number in your project

So how do we check the current WebPack version number?

npx webpack -v 
Copy the code

So we’re done with the two webPack installations.

Using webpack

mkdir webpack-demo
cd webpack-demo
npm init
Copy the code

Perform an initial configuration of webPack. I will enter some relevant information as prompted, which I won’t explain here.

A package.json file is then generated in the project.

{
  "name": "webpack-demo", / / package name"version": "1.0.0", / / version"description": "this is my demo"/ / description"main": "index.js"// External references expose js files"scripts": {// Configure short commands"test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "axin", / / the author"license": "ISC"// Project license}Copy the code

We can do a series of configurations on the generated file

{
    "private": true// Private project... }Copy the code

You can also use a simpler command that will automatically generate a default configuration item for you.

npm init -y
Copy the code

These are the two ways we can generate package.json for our project.

Webpack configuration

Although we use WebPack simply, it may be a few lines of code, so how does it help us to achieve file packaging? In fact, he is using the default configuration given by WebPack, so how do we use our own configuration? Add webpack.config.js to the project root directory

touch webpack.config.js
Copy the code

As mentioned above, NPX webpack index.js will pack the contents of the index.js file for you, but if we type NPX webpack it will get an error because we don’t say which file we will pack.

const path = require('path'); Exports = {entry: // Imports path module.exports from nodejs'./index.js'Output: {filename:'bundle.js'Path: path.resolve(__dirname,'bundle'__dirName a path to the current folder}}Copy the code

So we will do a series of configuration directly to webpack.config.js, I have detailed comments, you can see at a moment, when we run NPX webpack, we can directly package index.js. And generate the bundle folder and bundle.js.

Here we are using webpack.config.js as our configuration file, so how can we customize our own configuration file name?

// Use webPackconfig.js as the package configuration file NPX webpack --config webPackconfig.jsCopy the code

Organize files

We have already used basic commands to operate Webpack, but the files may be messy. For example, bundles and other files belong to package files, and xx.js and other resources files, so we will wait for the files to do a series of cleaning.

Delete the bundle folder, create a new SRC folder, and set the

index.js
header.js
slider.js
footer.js
Copy the code

Place it in the SRC folder as a resource file.

So after the change, we are going to configure webpack.config.js to consolidate the previous action.

// Change the configuration file name to NPX webpack --config webpack.config.js // Const path = require('path'); Exports = {entry: // Imports path module.exports from nodejs'./src/index.js'// start with index.js below SRC.'main.js'Path: path.resolve(__dirname,'dist'), // package to dist folder}} // index.html to introduce <! DOCTYPE HTML > < HTML > <head> <title> My page </title> </head> <body> <div id="root"></div>
</body>
<script type="text/javascript" src="./dist/main.js"></script>
</html>
Copy the code

Customize the packaging command

We now package using the NPX webpack command, but in some other frameworks, use the NPX webpack command

npm run build
Copy the code

So how do we configure this thing, as you may have noticed in my comments above, in the package.json file there is a scripts configuration item, and in this configuration item we can configure some of our own commands.

{
  "name": "webpack-demo"."version": "1.0.0"."description": "this is my demo."."private": true."scripts": {
    "build": "webpack"// Use NPM run build package equivalent to NPX webpack},"author": "axin"."license": "ISC"
}
Copy the code

Package output details

After we pack, we’re going to type in the package related content, so let’s see what that content is.

value explain
Hash Unique hash value for this package
version Webpack version number used for this packaging
time Overall packaging time
built at: Packaging time
asset Package file name
size Package file size
chunks The package ID value of the file
chunk names The name of the file
entrypoint main Package entry file
File list List of packaged file names

1. What is mode in warning? Mode is actually a package compression mode that we are configuring, if we write mode directly

mode: 'production'// production compression development does not compress the packaged codeCopy the code

In this way, there will be no warning problems during packaging.

2. Where did the main in Chunk names come from? **entry: ‘./ SRC /index.js’**

entry: {
    main: './src/index.js'
}
Copy the code

conclusion

NPM install webpack webpack-cli -g NPM install [email protected] webpack-cli -d // 2. NPX webpack index.js // 3. Webpack configuration file package.json // 4. Package the configuration file webpack.config.js and declare the configuration file name NPX webpack --config xx // 5. Custom package command scripts: {} // 6. Package output detailsCopy the code

It took me about 4 hours to write, and I may not be able to express myself well. I will try my best to improve my writing level. If this article is helpful to you, please give me a thumbs up and support. The next Webpack article will be published soon, looking forward to your attention.