What exactly does Webpack do
Webpack is really just a packaging tool. It can convert all kinds of current mainstream sASS, less, TSX, VUE, JSX, JSON, PNG, SVG and other files into HTML, CSS, JS and image resource files that can be recognized by the browser. Bundle them together by dependencies and export them to a bundle.
Create package.json
Webpack first creates a webpack-test folder locally, then opens the command prompt, goes to this directory, and executes the command NPM init (NPM is a package management tool that comes with Node.js.
Install the Wepack module
Now that you have the package file to document the project’s operations, you’re ready to start. If you didn’t exit the webpack-test directory on the command line, run the command
npm install --save-dev webpack webpack-cli --registry=https://registry.npm.taobao.org
(-) registry=https://registry.npm.taobao.org
This configuration is to solve the problem of slow download speed of NPM module, and sometimes the download may fail to install Webpack and Webpack-CLI (these two plug-ins are necessary, Webpack is a packaging tool, Webpack-cli is a user-friendly scaffolding for handling webpack commands.
Create resource directory SRC
Index. Js file
import './styles.css';
function component() {
var element = document.createElement('div');
var button = document.createElement('button');
var br = document.createElement('br');
console.log(_.join(['Hello1'.'providePlugin'].' '));
button.innerHTML = 'Click me1 lok at the console!';
element.appendChild(br);
element.appendChild(button);
// Lazy loading, not to load the corresponding JS resource file when the page is opened for the first time, when the event is triggered to load the resource file
// webpackChunkName This annotation is used to name lazy-loaded resource files, otherwise they will be named incrementally
button.onclick = e= > import(/* webpackChunkName: "math" */ './math').then(module= > {
var print = module.default;
print();
});
return element;
}
document.body.appendChild(component());
Copy the code
main.js
console.log(
'The print.js module has loaded! See the network tab in dev tools... '
);
export function square(x) {
return x * x;
}
export function cube(x) {
return x * x * x;
}
export default() = > {console.log('Button Clicked: Here\'s "some text"! ');
}
Copy the code
Styles. CSS file
body{
background-color: aquamarine
}
Copy the code
Directory screenshot:
Next we configure the WebPack configuration file and display the contents of the Index file in the browser. If you look at this, you may have a question: how does this directory show up in the browser when it doesn’t even have an HTML file under it? If you’ve seen the tutorials on the website or some of the step-by-step webPAC tutorials in other communities, this folder does have an HTML file in the beginning, but we’ve omitted it in 10 minutes to get started, for reasons explained in the title below.
4. Webpack configuration file
1. Add three files in the webpack-test root directory
webpack.common.js
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
module.exports = {
entry: {
index: './src/index.js'
},
output: {
filename: '[name].[hash].js'.path: path.resolve(__dirname, 'dist'),
// publicPath:'/' // This path will be used for exporting HTML files to import the associated file path
},
optimization: {
// Extract common code blocks to optimize package size requirements
splitChunks: {
cacheGroups: {
commons: {
name: "commons".// Common block name
chunks: "initial".minChunks: 1}}}},plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: 'Production'
}),
new webpack.ProvidePlugin({
_: 'lodash' // Global variable whole lodash
// join: ['lodash', 'join'})].module: {
rules: [{test: /\.css$/.use: ['style-loader'.'css-loader'] {},test: /\.(png|svg|jpg|gif)$/.use: ['file-loader'] {},test: /\.(woff|woff2|eot|ttf|otf)$/.use: ['file-loader'}]}};Copy the code
webpack.dev.js
const common = require('./webpack.common.js');
const merge = require('webpack-merge');
const webpack=require('webpack');
module.exports =env= > {
// Use env.<YOUR VARIABLE> here:
console.log('come') // 'local'
console.log('Production: ') // true
return merge(common, {
mode:'development'.devtool: 'inline-source-map'.// Enable this to debug code in the development environment
devServer: {
contentBase: "./dist".compress: true.port: 3000.hot:true
},
plugins: [new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin()// When these two plug-ins are used in a development environment, the page automatically refreshes after modifying the saved code]}); }Copy the code
webpack.prod.js
const common = require('./webpack.common.js');
const merge = require('webpack-merge');
// const UglifyJsPlugin =require('uglifyjs-webpack-plugin');
module.exports = merge(common, {
devtool: 'source-map'.// Enable this to debug code in production
// plugins:[
// new UglifyJsPlugin({// Tried to compress the code, but failed to find the cause
// sourceMap: false
/ /})
/ /,
mode:'production'
});
Copy the code
2. Add two scripts to the package.json file
"build": "webpack --config webpack.prod.js"."start": "webpack-dev-server --open --config webpack.dev.js".Copy the code
The complete content of package.json at this point is:
{
"name": "wbpack-test"."version": "1.0.0"."description": ""."main": "index.js"."scripts": {
"test": "echo \"Error: no test specified\" && exit 1"."build": "webpack --config webpack.prod.js"."start": "webpack-dev-server --open --config webpack.dev.js"
},
"author": ""."license": "ISC"."devDependencies": {
"webpack": "^ 4.34.0"."webpack-cli": "^ 3.3.4." "}}Copy the code
5. Start packing
After so much foreshadowing in front of us, we finally arrived at the main packaging link, without saying much, directly start.
Again, use the command prompt to go to the webpack-test directory and run the following command:
npm run build
Copy the code
This command tells the webpack packaging tool to execute the build script of the scripts object in package.json, which is actually webpack –config webpack.prod.js.
Js is the default configuration file used by the webpack packaging tool. If we do not want to use the default configuration file, we can use the webpack.config.js command. You can change the webPack configuration item file using the –config configuration.
Here’s how it works:
Because the code inside some dependency module is not installed, so let’s install our configuration item and code inside various dependencies.
We examined the code and configuration item files, found missing modules, and then ran the script to install them
install --registry=https://registry.npm.taobao.org --save-dev clean-webpack-plugin html-webpack-plugin css-loader file-loader style-loader webpack-merge
The script above contains -dev and is installed in the devDependencies property of the package.json file
The following script is installed in the Dependencies property
install --registry=https://registry.npm.taobao.org --save lodash
The package.json file after installation now looks like this:
DevDependencie and Dependencies
Json plug-ins installed with –save-dev are written to the devDependencies section of the package.json file, and plug-ins installed with –save are written to the Dependencies section. The devDependencies plug-in is only used in the development environment, not in the production environment, and it needs to be published in the production environment.
If you need to add jQuery dependencies to your project, write dependencies to add jQuery dependencies. Some of the build tools we use, such as Glup and WebPack, are packages that we use in development and don’t care about once they go live, so write it in devDependencies.
Then run the NPM run build command
You can see that the package is successful, and you have the packaged dist folder in the directory
Final test effect:
file:///D:/wbpack-test/dist/index.html
Copy the code
Six, multi-file entry packaging
Start by adding a printf.js file under the SRC folder
printf.js
console.log(
'The print.js module has loaded! See the network tab in dev tools... '
);
Copy the code
webpack.common.js
entry: {
index: './src/index.js'.print:'./src/print.js'
},
output: {
filename: '[name].[hash].js'.path: path.resolve(__dirname, 'dist'),
// publicPath:'/' // This path will be used for exporting HTML files to introduce the path of associated files
},
Copy the code
Finally, run the package command:
npm run build
As you can see, print.js is already printed to the dist folder.
Plug-in explain
Clean-webpack-plugin This plugin is used to clean up the cache files of the build directory.
Html-webpack-plugin – This plugin is used to generate entry HTML files to which dependencies are automatically added.
Merge Webpack-merge this is used to merge Webpack configuration files, why not apply object.assign? Because object. Assign cannot be deeply copied.
Webpack. NameModulesPlugin and Webpack HotModuleReplacementPlugin this two plug-ins are used together in the development environment, modified after saving code automatically refresh the page