webpack打包工具学习
1. 创建项目
mkdir webpack-demo && cd webpack-demo
npm init -y
npm install --save-dev webpack webpack-cli
2. 创建目录app
mkdir app && cd app
-
创建index.js
import _ from 'lodash';//若使用这个模块需要npm install lodash import vendors from './vendors'; function component() { const element = document.createElement('div'); element.innerHTML = _.join(['Hello', 'webpack']); vendors(); return element; } document.body.appendChild(component());
3. webpack.config.js配置
- 入口(entry)
入口起点(entry point)指示webpack应该使用哪一个模块来构建其内部的依赖图,是入口起点。默认值为./src
单个入口用法: entry: string | Array<string>
const path = require("path");
module.exports = {
entry: './app/index.js'
}
对象入口用法: entry: {[entryChunkName: string]|Array<string>}
module.exports = {
entry: {
app: './app/index.js',
vendors: './app/vendors.js'
}
}
-
输出(output)
可以控制webpack如何向硬盘写入编译文件。注意,即使可以存在多个
入口起点(entry point)
,但只能指定一个输出(output)
配置filename
用于输出文件的文件名path
输出目标目录的绝对路径
module.exports = {
entry: {
app: './app/index.js',
},
output: {
filename: 'bundle.js',
path: resolve('dist')
}
}
- 多个入口起点
module.exports = {
entry: {
app: './app/index.js',
vendors: './app/vendors.js'
},
output: {
filename: '[name].js',
path: resolve('dist')
},
}
4. 添加script命令
- 在package.json中的scripts字段,添加
"build": "webpack --config webpack.config.js"
,在命令窗口中运行npm run build
构建项目,可以看到目录中多出来了dist文件,并在下面生成了bundle.js文件
5. 生成完整的index.html打包文件
- 安装html-webpack-plugin
npm install html-webpack-plugin --save-dev
- 在app目录下添加index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Webpack-Demo</title>
</head>
<body>
</body>
</html>
- 在webpack.config.js中添加plugins属性
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
function resolve(relatedPath) {
path.resolve(__dirname, relatedPath);
}
module.exports = {
entry: {
app: './app/index.js',
vendors: './app/vendors.js'
},
output: {
filename: '[name].js',
path: resolve('dist')
},
plugins: [
new HtmlWebpackPlugin({template: './app/index.html'})
]
}