这些应该是对在官网初学习的一个小总结吧~,大家可以去官网看较为详细的解释:
指南 | webpack 中文网 (webpackjs.com)
那我们话不多说,直接开始:
- 首先在nodeJs下创建一个webpack-demo文件夹,在其中调用命令行执行:
npm init -y
npm install webpack webpack-cli --save-dev
- 修改生成的package.json:删去package.json中的
"main":"index.js"
,添加"private":true
,得到的结果应该如下:
{
"name": "webpack-demo2",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack-cli": "^4.9.1"
}
}
-
(创建一个bundle文件),在webpack-demo目录下创建src和dist文件夹
在src中放置书写和编辑的代码,即index.js
在dist中放置产生的代码最小化和优化后的“输出”目录,即index.html
得到的项目逻辑为:
webpack-demo |- package.json |- /dist |- index.html |- /src |- index.js
-
为了在index.js中打包lodash依赖,需要在该webpack-demo文件夹所在的nodeJs下使用命令行执行:
npm install --save lodash
- 在index.js中写入:
import _ from 'lodash';
function component() {
var element = document.createElement('div');
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
return element;
}
document.body.appendChild(component());
- 在index.html中写入:
<!doctype html>
<html>
<head>
<title>起步</title>
</head>
<body>
<script src="./bundle.js"></script>
</body>
</html>
- 在目录下添加配置文件webpack.config.js(使输入高效):
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
- 在该webpack-demo目录下用命令行输入如下内容,通过新配置文件再次执行构建:
npx webpack --config webpack.config.js
得到的项目逻辑如下:
webpack-demo
|- package.json
|- webpack.config.js
|- /dist
|- index.html
|- /src
|- index.js
到这一步,实现的效果就是打开index页面,会出现hello webpack
- 为了更快捷地运行webpack,我们可以在package.json中添加npm运行脚本,即添加
"build":"webpack"
:
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"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
大功告成!