What is WebPack
WebPack is mainly used for module packaging.
What it does is to analyze the project structure, find JavaScript modules and other extension languages (Scss, TypeScript, etc.) that browsers cannot directly run, and package them into a suitable format for browser use.
Official website address: official website
Five core concepts of webpack
Entry
The entry (entry) instructs webpack which file to use as the entry point to start packaging, and analyzes and builds the internal dependency graph.
Output
The output (output) instructs webpack where to output the packaged resource bundles and how to name them.
Loader
Loader enables webpack to process those non-javascript files, (such as translating pictures and css into files that webpack can understand) (webpack itself can only understand javascript)
Plugins
Plugins can be used to perform a wider range of tasks. Plugins range from packaging optimization and compression, all the way to redefining variables in the environment.
Mode
Practical examples of WebPack usage
First create a directory, initialize npm, then install webpack locally, then install webpack-cli (this tool is used to run webpack on the command line):
npm init -y
npm install webpack webpack-cli --save-dev
After the installation is complete:
Now add the script src/index.js
:
import _ from 'lodash'
function component() {
const element = document.createElement('div');
// lodash(目前通过一个 script 引入)对于执行这一行是必需的
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
return element;
}
document.body.appendChild(component());
Because lodash dependencies are packaged in index.js, we need to install the library locally:
npm install --save lodash
add index.html
:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>起步</title>
</head>
<body>
< <script src="dist/main.js"></script>
</body>
</html>
Finally add a configuration file webpack.config.js
:
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
},
};
The current directory structure is:
Finally, execute the packaging command:
$ npx webpack --config webpack.config.js
Generated after packagingmain.js