Table of contents
Test installation was successful:
(2) Create a directory named modules for placing resource files such as JS modules
(3) Create a module file hello.js under modules
(8) Open index.html directly to output the result!
1. Install Webpack
WebPack is a module loader and packaging tool, which can process and use various resources, such as JS, JSX, ES6, SASS, LESS, images, etc., as modules
install :
npm install webpack -g
npm install webpack-cli -g
Test installation was successful:
webpack -v
webpack-cli -v
Configuration :
- entry: entry file, specify which file Web Pack uses as the entry of the project
- output: output, specifying that WebPack puts the processed file to the specified path
- module: module for processing various types of files
- plugins: plugins, such as: hot update, code reuse, etc.
- resolve: Set the path to point to
- watch: monitor, used to package directly after setting the file changes
module.exports = {
entry:"",
output:{
path:"",
filename:""
},
module:{
loaders:[
{test:/\.js$/,;\loade:""}
]
},
plugins:{},
resolve:{},
watch:true
}
Directly run webpack
the command package
2. Use webpack
(1) Create a project
Create a folder webpack-study in 2021 study, and then open it with IDEA
(2) Create a directory named modules for placing resource files such as JS modules
(3) Create a module file hello.js under modules
//暴露一个方法
exports.sayHi = function () {
//输出:山姆看英语
document.write("<h1>山姆看英语1</h1>")
};
exports.sayHi1 = function () {
//输出:山姆看英语2
document.write("<h1>山姆看英语2</h1>")
};
exports.sayHi2 = function () {
//输出:山姆看英语3
document.write("<h1>山姆看英语3</h1>")
};
exports.sayHi3 = function () {
//输出:山姆看英语4
document.write("<h1>山姆看英语4</h1>")
};
exports.sayHi4 = function () {
//输出:山姆看英语5
document.write("<h1>山姆看英语5</h1>")
};
(4) Create an entry file main.js named main.js under modules to set the entry attribute when packaging
//引入hello.js
let hello = require("./hello");
hello.sayHi();
(5) Create a webpack.config.js configuration file in the project directory and use the webpack command to package
module.exports = {
//entry:这个就是程序的入口
entry: './modules/main.js',
//输出
output: {
filename: "./js/bundle.js"
}
};
(6) Packing
Note: If packaging fails, run webpack with administrator privileges
(7) Create an HTML page in the project directory, such as index.html, and import the JS file packaged by webpack
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Java</title>
</head>
<body>
<script src="dist/js/bundle.js"></script>
</body>
</html>
(8) Open index.html directly to output the result!
Note :
# 参数--watch 用于监听变化,如果要打包的东西有变化,就重新打包
webpack --watch