webpack 的作用
- 前端项目构建/打包工具,可以解决目前 vue 开发的困境
- 提供了友好的模块化支持,代码压缩混淆,解决 js 兼容问题,性能优化 等特性
- 提高了开发效率 和 项目的可维护性
步骤
1. 初始化包管理工具 npm init -y
命令,初始化包管理工具 package.json
2. 默认源代码目录是 src 文件夹,所以先创建一个 src 文件夹(后面可以改)
3. 安装 和 配置
npm install webpack webpack-cli -D
运行指令进行安装- 在项目根目录中 创建名为 webpack.config.js 的 webpack 配置文件
- 在 webpack 的配置文件中,初始化如下配置
module.exports = { mode:'development' // mode 用来指定构建模式:development 开发模式 production 生产模式 }
- 在 package.json 配置文件中的 scripts 节点下,新增 dev 脚本
"scripts": {
"dev":"webpack"
}
- 在终端运行 npm run dev 命令 , 启动 webpack 进行项目打包
4. 配置打包的 入口 与 出口
- 默认的打包入口文件为 src -> index.js
- 默认的打包出口文件为 dist -> main.js
- 通过 webpack.config.js 设置入口/出口
const path = require("path")
module.exports = {
mode:"devlopment",
entry:path.join(__dirname,'./src/index.js')
output:{
path:path.join(__dirname,"./dist"),
filename:"res.js"
}
}
其他方便的补充
1. 配置 webpack 的自动打包功能
- 安装支持项目自动打包的工具
npm install webpack-dev-server -D
- 修改 [ackage.json -> script 中的 dev 命令
"script":{
"dev":"webpack-dev-server"
}
- 将引用的输出文件的路径 改成再根节点下 因为会生成一个不可见的文件 在项目的根目录下,同时生成文件的名称是输出文件的名称 默认为 main.js
- 运行
npm run dev
命令,重新进行打包 - 在浏览器中访问 http://localhost:8080 地址,查看自动打包效果
2. 配置 html-webpack-plugin 生成预览页面
- 运行
npm i html-webpack-plugin -D
命令,安装生成预览页面的插件 - 修改 webpack.config.js 文件头部区域,添加信息
这个index.html 会自动引入根目录中的输出文件 可以将文件中的引用文件删掉
const HtmlWebpackPlugin = require('html-webpack-plugin')
const htmlPlugin = new HtmlWebpackPlugin({
template:'./src/index.html',
filename:'index.html'
})
- 修改 webpack.config.js 文件中向外暴露的配置对象,新增一个节点
module.exports = {
plugin:[htmlPlugin]
}
- 配置自动打包的参数 在package.json 中
"scripts": { "dev":"webpack-dev-server --open --host 127.0.0.1 --port 8888" }
- ip 一般是 127.0.0.1, localhost
- port 默认是 8080 可以修改为 8888
使用webpack打包 然后测试模块的速度 压缩文件 引入cdn
vue.config.js配置项
module.exports = {
publicPath: "./",
outputDir: "dist",
assetsDir: "static",
indexPath: "index.html",
filenameHashing: true,
pages: {
index: {
entry: 'src/index/main.js',
template: 'public/index.html',
filename: 'index.html',
title: 'Index Page',
chunks: ['chunk-vendors', 'chunk-common', 'index']
},
subpage: 'src/subpage/main.js'
},
lintOnSave: true,
runtimeCompiler: false,
transpileDependencies: [ ],
productionSourceMap: true,
crossorigin: "",
integrity: false,
configureWebpack: () => {},
chainWebpack: () => {},
devServer: {
open: process.platform === 'darwin',
host: '0.0.0.0',
port: 8080,
https: false,
hotOnly: false,
proxy: {
'/api': {
target: "http://app.rmsdmedia.com",
changeOrigin: true,
secure: false,
pathRewrite: {
"^/api": ""
}
},
'/foo': {
target: '<other_url>'
}
},
before: app => {}
},
css: {
extract: true,
sourceMap: false,
loaderOptions: {
css: {
},
postcss: {
}
},
modules: false
},
parallel: require('os').cpus().length > 1,
pwa: {},
pluginOptions: {
}
}
提升打包性能的文章 很全很清晰