demo
cd webpack-demo
//初始化
npm init -y
//安装webpack webpack-cli
npm install webpack webpack-cli --save-dev
创建一下目录结构
webpack-demo
|- package.json
+ |- /dist
+ |- index.html
+ |- /src
+ |- index.js
Tip 目前手动创建index.html,后续讲解自动打包生成
src/index.js
安装lodash依赖
npm install --save lodash
import _ from 'lodash';
function component() {
const element = document.createElement('div');
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
return element;
}
document.body.appendChild(component());
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>起步</title>
</head>
<body>
<script src="main.js"></script>
</body>
</html>
package.json
{
"name": "webpack-demo02",
"version": "1.0.0",
"description": "",
- "main": "index.js",
+ "private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^5.50.0",
"webpack-cli": "^4.8.0"
}
}
打包
npx webpack
在浏览器中打开 dist 目录下的 index.html,如果一切正常,你应该能看到以下文本:’Hello webpack’
配置webpack.config.js
project
webpack-demo
|- package.json
+ |- webpack.config.js
|- /dist
|- index.html
|- /src
|- index.js
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
},
};
打包
npx webpack --config webpack.config.js
Tip 如果 webpack.config.js 存在,则 webpack 命令将默认选择使用它。我们在这里使用 —config 选项只是向你表明,可以传递任何名称的配置文件。这对于需要拆分成多个文件的复杂配置是非常有用的。
npm scripts
考虑到用 CLI 这种方式来运行本地的 webpack 副本并不是特别方便,我们可以设置一个快捷方式。调整 package.json 文件,添加一个 npm script:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
+ "build": "webpack"
},
npm run build