基本安装
首先建一个你的项目工程目录,初始化npm,在本地安装webpack以及webpack-cli
mkdir webpack-demo
cd webpack-demo
npm init -y
npm install webpack webpack-cli --save-dev
现在进入该项目目录,创建下面这个目录结构
webpack-demo
????|- package.json
+??|- index.html
+??|- /src
+???? |- index.js
src/index.js
function component() {
var element = document.createElement('div');
// Lodash(目前通过一个 script 脚本引入)对于执行这一行是必需的
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
return element;
}
document.body.appendChild(component());
index.html
<!doctype html>
<html>
<head>
<title>起步</title>
<script src="https://unpkg.com/[email protected]"></script>
</head>
<body>
<script src="./src/index.js"></script>
</body>
</html>
调整package.json,确保安装包是私有的(private)
{
"name": "webpack-demo",
"version": "1.0.0",
+ "description": "",
"private": true,
"main": "index.js", //官网说把这个删了,然而删除后就编译失败了
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^4.0.1",
"webpack-cli": "^2.0.9"
},
"dependencies": {}
}
新建一个目录用于存放分发代码,也就是我们打包后的文件,与我们编写代码的src目录分离,目录结构如下:
webpack-demo
??|- package.json
+?|- /dist
+????|- index.html
-?|- index.html
??|- /src
???? |- index.js
在本地安装依赖,脚本中添加lodash依赖
npm install --save lodash
src/index.js
+ import _ from 'lodash';
+
function component() {
var element = document.createElement('div');
- // Lodash, currently included via a script, is required for this line to work
+ // Lodash, now imported by this script
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
return element;
}
document.body.appendChild(component());
更新 index.html 文件,修改 script标签来加载 bundle,而不是原始的 /src 文件:
dist/index.html
<!doctype html>
<html>
<head>
<title>起步</title>
- <script src="https://unpkg.com/[email protected]"></script>
</head>
<body>
- <script src="./src/index.js"></script>
+ <script src="main.js"></script>
</body>
</html>
在项目内执行命令npx webpack 以src目录下的index.js作为入口起点,输出为main.js,此时我们执行index.html就可以看到 ‘Hello webpack’
使用一个配置文件
在项目根目录下新建一个webpack.config.js配置文件
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js', //项目入口文件
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist') //输出文件路径
}
};
为了方便使用webpack修改package.json添加npm脚本
package.json
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
+ "build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^4.0.1",
"webpack-cli": "^2.0.9",
"lodash": "^4.17.5"
}
}
这样我们就可以使用npm run build代替npx命令
PS:以上是根据webpack官网案例学习记录一下自己的理解,如有错误请指正。
原文地址:https://www.cnblogs.com/yanggl/p/10291908.html