In this article we will take a look at the basic use of WebPack through a small Demo
Introduction to 1,
First we create an empty directory, Demo, as the root folder of the project
Run the NPM init command in the directory to initialize the package.json file
> npm init -y # Initialize package.json file with default
Copy the code
We can then install webPack through NPM
> npm install --save-dev webpack
Copy the code
If you are using the WebPack 4+ version, you will also need to install WebPack-CLI
> npm install --save-dev webpack-cli
Copy the code
Next, we create two folders in the root directory, dist (for managing output files) and SRC (for managing resource files)
The SRC folder is for your code files, and the dist folder is for your packaged files, or more specifically, for your distribution files
Create the index.html file in the dist folder and write the following code
<! doctypehtml>
<html>
<head>
<title>Demo</title>
</head>
<body>
<! -- the main. Js file referenced here will be generated after packaging -->
<script src="main.js"></script>
</body>
</html>
Copy the code
Create the index.js file in the SRC folder and write the following code
// Reference the LoDash module, which webPack together
// Since lodash is an external module, you need to install it first: NPM install --save Lodash
import _ from 'lodash';
function component() {
var element = document.createElement('div');
element.innerHTML = _.join(['Hello'.'webpack'].' ');
return element;
}
document.body.appendChild(component());
Copy the code
At this point, the directory structure of the folder is as follows
Demo
- package.json
- package-lock.json
+ node_modules
+ src
- index.js
+ dist
- index.html
Copy the code
Ok, at this point we run the webpack package, which packs/SRC /index.js and prints it to /dist/main.js
> npx webpack
> /node_modules/.bin/webpack
> Run the binary file 'node_modules\.bin\webpack' on Windows
Copy the code
After that, we should see a main.js file generated in the dist directory
Then, open the index.html file in the dist directory in your browser and you should see the text of Hello Webpack
2. Configuration files
So far, we’ve used the default webPack configuration, such as import files and output files
If you want a richer custom configuration, you can also write your own configuration file, webpack.config.js
Webpack will read it automatically, and now the file structure of the entire project looks like this
Demo
- package.json
- package-lock.json
- webpack.config.js
+ node_modules
+ src
- index.js
+ dist
- index.html
Copy the code
Then we write down the configuration in the webpack.config.js file
const path = require('path');
module.exports = {
// Import file
entry: './src/index.js'.// Output file
output: {
filename: 'bundle.js'.// Here we'll name the output file bundle.js
path: path.resolve(__dirname, 'dist')}};Copy the code
Since the output file name has changed after packaging, we also need to go to /dist/index.html to change the referenced file name
<! doctypehtml>
<html>
<head>
<title>Demo</title>
</head>
<body>
<! -- change the referenced file to bundle.js -->
<script src="bundle.js"></script>
</body>
</html>
Copy the code
Finally, we pack with WebPack and use the specified configuration file
> npx webpack --config webpack.config.js
Copy the code
As you can see, running the command generates a bundle.js file in the dist directory
Also, open the index.html file in the dist directory with a browser and you should see the text of Hello Webpack
This proves that the configuration file is in effect
3. NPM command
Typically webPack start commands attach multiple parameters, so each build requires a long list of commands to enter
This is too much work, so we can add a build command to the script in package.json
{
"name": "Demo"."version": "1.0.0"."description": ""."main": "index.js"."scripts": {
"test": "echo \"Error: no test specified\" && exit 1"."build": "webpack --config webpack.config.js"
},
"keywords": []."author": ""."license": "ISC"."devDependencies": {
"webpack": "^ 4.39.2"."webpack-cli": "^ 3.3.7." "
},
"dependencies": {
"lodash": "^ 4.17.15"}}Copy the code
Then, when it’s time to run the build command, just type the command NPM run build
4. Manage resources
Webpack can only understand JavaScript modules, but loader can also import other types of files
Let’s take importing CSS files as an example. To handle CSS, we need to use style-loader and CSS-loader
> npm install --save-dev style-loader css-loader
Copy the code
Processing rules are then specified in the configuration file webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js'.output: {
filename: 'bundle.js'.path: path.resolve(__dirname, 'dist')},module: {
rules: [{// Specify the file to process
test: /\.css$/.// Specify the loader to use
use: [
'style-loader'.'css-loader'}]}};Copy the code
Ok, then we can start to write the style file, the directory structure is as follows
Demo
- package.json
- package-lock.json
- webpack.config.js
+ node_modules
+ src
- index.js
- index.css
+ dist
- index.html
Copy the code
The contents of the index. CSS file are as follows
.hello {
color: red;
}
Copy the code
Then add index.css to the index.js file (as a module)
import _ from 'lodash';
// Import the CSS file
import './index.css';
function component() {
var element = document.createElement('div');
element.innerHTML = _.join(['Hello'.'webpack'].' ');
element.classList.add('hello'); // Add styles
return element;
}
document.body.appendChild(component());
Copy the code
Finally, run the build command NPM run build to package the project
At this point, open the /dist/index.html file in your browser and you should see the text turn red
5. Manage output
We can use plug-ins to manage output, using the clean-Webpack-plugin plug-in as an example
Remember that before we created the webpack.config.js file, the default output file after packaging was main.js
Since then, the file has remained in the /dist directory (assuming it hasn’t been removed manually), which is quite unscientific
So we can use the clean-webpack-plugin to automatically clean up unwanted files after repackaging
First, let’s install the plug-in
> npm install --save-dev clean-webpack-plugin
Copy the code
Then configure it in the webpack.config.js file
const path = require('path');
Note that introducing the CleanWebpackPlugin requires destructuring syntax
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
entry: './src/index.js'.output: {
filename: 'bundle.js'.path: path.resolve(__dirname, 'dist')},module: {
rules: [{test: /\.css$/,
use: [
'style-loader'.'css-loader']]}},// Use plugins
plugins: [
// Delete all files in the specified output.path directory and rebuild the package
new CleanWebpackPlugin({
// Specify files to be deleted and files not to be deleted, use! Specify files not to be deleted
cleanOnceBeforeBuildPatterns: ['*.js'.'! index.html']]}});Copy the code
Ok, rerun the build command at this point
> npm run build
Copy the code
There are only two files left in the dist folder, index. HTML and bundle.js