VUE2.7项目配置webpack打包-详细操作步骤

一、Webpack简介

  Webpack是一个打包工具,可以把JS、CSS、Node Module、Coffeescrip、SCSS/LESS、图片等都打包在一起,因此,现在几乎所有的SPA项目、JS项目都会用到Webpack。

官网:https://webpack.js.org  

GitHub为https://github.com/webpack/ webpack 

二、创建基于Webpack的Vue2.7.js项目

  Webpack+Vue.js的方式来做项目的,这样才可以做到“视图”“路由”“component”等的分离,以及快速打包、部署及项目上线。

1. Webpack 的相关命令,以及项目常用到的命令,我全部放这里,请务必按照版本安装!!!

"cross-env": "^7.0.2",

"vue-template-compiler": "^2.6.14",

"webpack": "^5.70.0",

"webpack-dev-server": "^4.7.4"

"compression-webpack-plugin": "^9.2.0",

"css-loader": "^4.1.0",

"friendly-errors-webpack-plugin": "^1.7.0",

"is-glob": "^4.0.3",

"monaco-editor": "^0.27.0",

"monaco-editor-webpack-plugin": "^4.2.0",

"process": "^0.11.10",

"style-loader": "^3.3.1",

"stylus-loader": "^6.2.0",

"vue-loader": "^15.11.1",

"vue-style-loader": "^4.1.0",

"webpack-bundle-analyzer": "^4.5.0",

"webpack-cli": "^4.10.0",

"webpack-merge": "^5.8.0",

"webpackbar": "^5.0.2"

"cross-env": "^7.0.2",

package.json代码:

 "scripts": {"build:private": "cross-env CONFIG_ENV=private  webpack --config build/webpack.prod.js","start:private": "cross-env CONFIG_ENV=private  webpack-dev-server --open --hot --config ./build/webpack.dev.js"},

2. 文件配置 

看下文件目录结构:

1)build/config.js文件:

'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.const path = require('path')let env
switch (process.env.CONFIG_ENV) {case 'local':env = require('../config/local.env')breakcase 'dev':env = require('../config/dev.env')breakcase 'stage':env = require('../config/stage.env')breakcase 'pro':env = require('../config/prod.env')breakcase 'private':env = require('../config/private.env')breakdefault:break
}module.exports = {shouldAnalyzerBundle: false,shouldSplitChunks: false,shouldGzipResource: false,htmlWebpackConfig: {// author: 'AnbanTech@FrontendTeam',// license: 'Copyright © 2019-2022 Anban Inc. All Rights Reserved. 安般科技.',title: '报告'// keywords: 'webpack, vue',// descritpion: 'learn how to config webpack to build vue project'}
}

 2)build/webpack.base.js文件:(重点分析)

const path = require('path')
const { resolve } = path
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { htmlWebpackConfig, shouldSplitChunks } = require('./config')
const WebpackBar = require('webpackbar')
const { VueLoaderPlugin } = require('vue-loader')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin')const isDev = process.env.NODE_ENV !== 'production'
function genereateAssetsLoader(shouldSplitChunks) {if (shouldSplitChunks) {return [{test: /\.(woff|woff2|eot|otf|ttf)$/,type: 'asset',generator: {filename: 'font/[hash][ext][query]'}},{test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,type: 'asset/resource',generator: {filename: 'images/[hash][ext][query]'}},{test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,type: 'asset/resource',generator: {filename: 'media/[hash][ext][query]'}}]} else {return [{test: /\.(woff|woff2|eot|otf|ttf)$/,type: 'asset/inline'},{test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,type: 'asset/inline'},{test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,type: 'asset/inline'}]}
}module.exports = {target: 'web',stats: {chunks: false,chunkModules: false,modules: false,children: false,timings: false,assetsSort: 'name',performance: false},entry: {app: resolve('src/main.ts')},output: {path: resolve('dist'),filename: shouldSplitChunks ? 'lib/[name].[chunkhash:8].js' : 'lib/bundle.js',publicPath: './',clean: true},resolve: {extensions: ['.js', '.vue', '.json', '.ts'],alias: {'@': path.resolve('src'),vue$: 'vue/dist/vue.esm.js'}},module: {rules: [{test: /\.ts$/,loader: 'ts-loader',exclude: /node_modules/,options: {appendTsSuffixTo: [/\.vue$/],transpileOnly: true}},{test: /\.vue$/,loader: 'vue-loader'},{test: /\.js$/,loader: 'babel-loader',options: {cacheDirectory: true},exclude: /node_modules/},{test: /\.md/,type: 'asset/source'},{test: /\.styl(us)?$/,use:!shouldSplitChunks || isDev? ['vue-style-loader', 'css-loader', 'stylus-loader']: [MiniCssExtractPlugin.loader, 'css-loader', 'stylus-loader']},{test: /\.css$/,use:!shouldSplitChunks || isDev? ['vue-style-loader', 'css-loader']: [MiniCssExtractPlugin.loader, 'css-loader']}].concat(genereateAssetsLoader(shouldSplitChunks))},plugins: [new MonacoWebpackPlugin({languages: ['c']}),new VueLoaderPlugin(),new HtmlWebpackPlugin(Object.assign({}, htmlWebpackConfig, {filename: 'index.html',title: 'webpack测试',template: path.resolve('public/index.html'),minify: {removeAttributeQuotes: true,collapseWhitespace: true,removeComments: true,collapseBooleanAttributes: true,collapseInlineTagWhitespace: true,removeRedundantAttributes: true,removeScriptTypeAttributes: true,removeStyleLinkTypeAttributes: true,minifyCSS: true,minifyJS: true,minifyURLs: true,useShortDoctype: true}})),shouldSplitChunks &&new MiniCssExtractPlugin({filename: 'css/[name].[contenthash:8].css',chunkFilename: 'css/[name].[contenthash:8].css'}),new CopyWebpackPlugin({patterns: [{from: resolve('public'),globOptions: {ignore: ['**/index.html', '**/.DS_Store']}},{from: path.resolve(__dirname, '../static'),to: 'static',globOptions: {ignore: ['.*']}}]}),new WebpackBar({name: '正在打包',color: '#fa8c16'}),new FriendlyErrorsWebpackPlugin({clearConsole: true}),// new BundleAnalyzerPlugin({//   analyzerHost: '127.0.0.1',//   //  将在“服务器”模式下使用的端口启动HTTP服务器。//   analyzerPort: 8888, //   //  路径捆绑,将在`static`模式下生成的报告文件。//   //  相对于捆绑输出目录。//   reportFilename: 'report.html',//   defaultSizes: 'parsed',//   //  在默认浏览器中自动打开报告//   openAnalyzer: true,//   //  如果为true,则Webpack Stats JSON文件将在bundle输出目录中生成//   generateStatsFile: false, //   //  如果`generateStatsFile`为`true`,将会生成Webpack Stats JSON文件的名字。//   //  相对于捆绑输出目录。//   statsFilename: 'stats.json',//   //  stats.toJson()方法的选项。//   //  例如,您可以使用`source:false`选项排除统计文件中模块的来源。//   //  在这里查看更多选项:https:  //github.com/webpack/webpack/blob/webpack-1/lib/Stats.js#L21//   statsOptions: null,//   logLevel: 'info'  // 日志级别。可以是'信息','警告','错误'或'沉默'。// })].filter(Boolean)
}

 2)build/webpack.dev.js文件:(重点分析)

const webpack = require('webpack')
const path = require('path')
const { default: merge } = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base')
const config = require('./config')let env
switch (process.env.CONFIG_ENV) {case 'local':env = require('../config/local.env')breakcase 'dev':env = require('../config/dev.env')breakcase 'stage':env = require('../config/stage.env')breakcase 'pro':env = require('../config/prod.env')breakcase 'private':env = require('../config/private.env')breakdefault:break
}module.exports = merge(baseWebpackConfig, {mode: 'development',devtool: 'eval-cheap-module-source-map',cache: true,devServer: {static: false,devMiddleware: {publicPath: '/'},historyApiFallback: {rewrites: [{ from: /.*/, to: path.posix.join('/', 'index.html') }]},hot: true,compress: true,host: 'localhost',// 配置开发服务器的端口,默认为8080port: 3000,open: true,proxy: {'/Arrgemnt': {target: 'http://192.168.5.32:8031',// target: 'http://192.168.50.94:9050',changeOrigin: true},'/files': {target: 'http://192.168.5.32:21101',// target: 'http://192.168.50.94:9050',changeOrigin: true,pathRewrite: { '^/files': '' }},'/yh': {target: 'http://192.168.5.57:9050',// target: 'http://192.168.50.94:9050',changeOrigin: true},'/yh/analysis': {target: 'http://192.168.5.57:9050',ws: true,changeOrigin: true},'/abfuzz/': {target: 'http://192.168.5.57:21101',changeOrigin: true},},client: {logging: 'warn',overlay: false,progress: true,reconnect: true}},plugins: [new webpack.DefinePlugin({'process.env': env}),new webpack.ProvidePlugin({process: require.resolve('process/browser')})]
})

 3)build/webpack.prod.js文件:

const webpack = require('webpack')
const { default: merge } = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base')
const CompressionPlugin = require('compression-webpack-plugin')
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')
const { shouldAnalyzerBundle, shouldGzipResource, shouldSplitChunks } = require('./config')
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')let env
switch (process.env.CONFIG_ENV) {case 'local':env = require('../config/local.env')breakcase 'dev':env = require('../config/dev.env')breakcase 'stage':env = require('../config/stage.env')breakcase 'pro':env = require('../config/prod.env')breakcase 'private':env = require('../config/private.env')breakdefault:break
}console.log('process.env.CONFIG_ENV:', process.env.CONFIG_ENV)module.exports = merge(baseWebpackConfig, {mode: 'production',devtool: 'nosources-source-map', // productioncache: false,plugins: [new webpack.DefinePlugin({'process.env': env}),new webpack.ProvidePlugin({process: require.resolve('process/browser')}),shouldGzipResource &&new CompressionPlugin({filename: '[path][base].gz',algorithm: 'gzip',test: /\.(js|css)$/}),shouldAnalyzerBundle &&new BundleAnalyzerPlugin({analyzerMode: 'server',analyzerHost: '127.0.0.1',analyzerPort: 8889,reportFilename: 'report.html',defaultSizes: 'parsed',openAnalyzer: true,generateStatsFile: false,statsFilename: 'stats.json',statsOptions: null,logLevel: 'info'})].filter(Boolean),optimization: shouldSplitChunks? {runtimeChunk: true,minimize: true,minimizer: [`...`, new CssMinimizerPlugin()],splitChunks: {chunks: 'all',minChunks: 1,maxInitialRequests: 6,maxAsyncRequests: 6,cacheGroups: {commons: {test: /[\\/]node_modules[\\/]/,name: 'vendors',chunks: 'all'}}}}: {}
})

 4)config/dev.env.js文件:

'use strict'
const { default: merge } = require('webpack-merge')
const prodEnv = require('./prod.env')module.exports = merge(prodEnv, {NODE_ENV: '"development"',BASE_API: '"user-test.cosec.tech"',BASE_IP: '"47.100.28.180"',CONFIG_ENV: '"dev"'
})

 5)config/local.env.js文件:

'use strict'
const { default: merge } = require('webpack-merge')
const prodEnv = require('./prod.env')module.exports = merge(prodEnv, {NODE_ENV: '"development"',BASE_API: '""',BASE_IP: '""',CONFIG_ENV: '"local"'
})

 6)config/poc.env.js文件:

'use strict'
const { default: merge } = require('webpack-merge')
const prodEnv = require('./prod.env')module.exports = merge(prodEnv, {NODE_ENV: '"development"',BASE_API: '""',BASE_IP: '""',CONFIG_ENV: '"private"'
})

 7)config/private.env.js文件:

const { default: merge } = require('webpack-merge')
const prodEnv = require('./prod.env')module.exports = merge(prodEnv, {NODE_ENV: '"development"',BASE_API: '""',BASE_IP: '""',CONFIG_ENV: '"private"'
})

 8)config/prod.env.js文件:

'use strict'
module.exports = {NODE_ENV: '"development"',BASE_API: '"www.fuzzing.tech"',BASE_IP: '"43.248.189.190"',CONFIG_ENV: '"pro"'
}

 9)config/stage.env.js文件:

'use strict'module.exports = {NODE_ENV: '"development"',BASE_API: '"user-stage.cosec.tech"',BASE_IP: '"47.101.189.106"',CONFIG_ENV: '"stage"'
}

9)public/index.vue

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><link type="image/x-icon" rel="shortcut icon" href="data:;"><link type="image/x-icon" rel="shortcut icon" href="../logo.png"> <title><%= htmlWebpackPlugin.options.title %></title><meta name="author" content="<%= htmlWebpackPlugin.options.author %>"><meta name="license" content="<%= htmlWebpackPlugin.options.license %>"><meta name="description" content="<%= htmlWebpackPlugin.options.descritpion %>"><meta name="keywords" content="<%= htmlWebpackPlugin.options.keywords %>"><script src=./lib/data.js></script></head><body><div id="app"></div>
</body></html>

10) static 文件下有图片昂;

3.运行命令和打包命令:

npm run start:private

npm run build:private

完结撒花✿✿ヽ(°▽°)ノ✿

其实我写的过程,不断地出现报错,坚持住,不断地解决掉!!

当前配置有些冗余的代码文件,后续还需要优化

代码放在了gitee上: git@gitee.com:cathyli2021/vue2.7_webpack.git 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/851236.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

error 12154 received logging on to the standby报错处理

错误 处理方法 该参数不是主库的servicename &#xff08;低级错误&#xff09; SQL> alter system set log_archive_dest_2 SERVICEstandby ASYNC VALID_FOR(ONLINE_LOGFILES,PRIMARY_ROLE) DB_UNIQUE_NAMEstandby; System altered. 观察主库日志: 备库日志: 该问题会影…

vue2自定义指令

本节目标 快速入门v-loading 快速入门 指令对比 基本语法 使用: v-指令名"指令值"定义: 通过 directives 局部定义或者全局定义通过事件对象 el 可以拿到指令所在元素通过形参 binding 可以拿到指令的传值通过update钩子, 可以监听指令值的变化,进行更新操作 局部…

C++进阶:继承

文章目录 继承的概念继承的定义方式继承关系和访问限定符基类和派生类对象的赋值转换继承中的作用域派生类中的默认成员函数构造函数拷贝构造函数赋值拷贝函数析构函数 总结 继承的概念 继承(inheritance)机制是面向对象程序设计使代码可以复用的最重要的手段&#xff0c;它允…

一个开源的Office软件,很离谱的办公神器

你们平时用的办公软件是哪一个&#xff1f;今天给大家分享的是一个“进阶版”office工具ONLY OFFICE&#xff0c;不仅支持Windows、Mac、ios, 安卓等全平台满足你的日常所需&#xff0c;更是提供了大量开挂般的功能。 1、打工人省金币 你们平时使用办公软件最头疼的问题是什么…

第1章Hello world 3/5:Cargo.lock:确保构建稳定可靠:运行第一个程序

讲动人的故事,写懂人的代码 1.6 Cargo.lock:确保构建稳定可靠 “看!”席双嘉一边指着屏幕一边说,“终端窗口提示符的颜色,从绿变黄了。这就意味着代码在上次提交后有点变化。” 赵可菲:“但是我们只是运行了程序,代码应该没动呀。” 席双嘉敲了下git status -uall,这…

PawSQL优化 | 分页查询太慢?别忘了投影下推

​在进行数据库应用开发中&#xff0c;分页查询是一项非常常见而又至关重要的任务。但你是否曾因为需要获取总记录数的性能而感到头疼&#xff1f;现在&#xff0c;让PawSQL的投影下推优化来帮你轻松解决这一问题&#xff01;本文以TPCH的Q12为案例进行验证&#xff0c;经过Paw…

高考志愿填报的技巧和方法

高考过后&#xff0c;最让家长和学生需要重视的就是怎样填报志愿。高考完和出成绩之前有一段很长的时间&#xff0c;而成绩出来之后往往报考的时间非常的紧张。在很短的时间内&#xff0c;高考的学生和他的家长要综合高考的成绩&#xff0c;考虑院校&#xff0c;专业&#xff0…

Vue中的组件通信

父向子通信 1.定义props 子组件中&#xff0c;定义期望接收的属性。例如&#xff0c;在子组件的script部分&#xff1a; export default {props: {message: String // 假设父组件要传递一个字符串类型的数据} } 2.传递数据 在父组件的模板中&#xff0c;通过属性绑定的方式将…

分享: 动图网站

Stickers for iOS & Android | GIPHY 这个网站有一些外国的制作的动图

OOP面试问题 - C#

文章概述 背景问题答案概括 背景 以下是最流行的 OOP面试问题和答案的列表。这些 OOPS 面试问题适用于初学者和专业 C# 开发人员。 问题 什么是对象&#xff1f;什么是封装&#xff1f;什么是抽象&#xff1f;什么是继承&#xff1f;哪些是访问说明符&#xff1f;如何在 C…

PHP实现一个简单的接口签名方法以及思路分析

文章目录 签名生成说明签名生成示例代码签名校验示例代码 签名生成说明 B项目需要调用A项目的接口&#xff0c;由A项目为B项目分配 AccessKey 和 SecretKey&#xff0c;用于接口加密&#xff0c;确保不易被穷举&#xff0c;生成算法不易被猜测。 最终需要确保包含签名的参数只…

2 程序的灵魂—算法-2.4 怎样表示一个算法-2.4.6 用计算机语言表示算法

我们的任务是用计算机解题&#xff0c;就是用计算机实现算法&#xff1b; 用计算机语言表示算法必须严格遵循所用语言的语法规则。 【例 2.20】求 12345 用 C 语言表示。 main() {int i,t; t1; i2; while(i<5) {tt*i; ii1; } printf(“%d”,t); } 【例 2.21】求级数的…

12_1 Linux Yum进阶与DNS服务

12_1 Linux Yum进阶与DNS服务 文章目录 12_1 Linux Yum进阶与DNS服务[toc]1. Yum进阶1.1 自定义yum仓库1.2 网络Yum仓库 2. DNS服务2.1 为什么要使用DNS系统2.2 DNS服务器的功能2.3 DNS服务器分类2.4 DNS服务使用的软件及配置2.5 搭建DNS服务示例2.6 DNS特殊解析 1. Yum进阶 1…

32-读取Excel数据(xlrd)

本篇介绍如何使在python中读取excel数据。 一、环境准备 先安装xlrd模块&#xff0c;打开cmd&#xff0c;输入 pip install xlrd 在线安装。 二、基本操作 import xlrd# 打开excel表格 data xlrd.open_workbook(test.xlsx)# 2.获取sheet表格 # 方式一&#xff1a;通过索引顺…

RocketMq详解:二、SpringBoot集成RocketMq

在上一章中我们对Rocket的基础知识、特性以及四大核心组件进行了详细的介绍&#xff0c;本章带着大家一起去在项目中具体的进行应用&#xff0c;并设计将其作为一个工具包只提供消息的分发服务和业务模块进行解耦 在进行本章的学习之前&#xff0c;需要确保你的可以正常启动和…

【算法篇】滑动窗口的最大值JavaScript版

滑动窗口的最大值 题目描述&#xff1a; 给定一个长度为 n 的数组 num 和滑动窗口的大小 size &#xff0c;找出所有滑动窗口里数值的最大值。 例如&#xff0c;如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3&#xff0c;那么一共存在6个滑动窗口&#xff0c;他们的最大值…

Linux Kernel入门到精通系列讲解(RV-Kernel 篇) 5.4 添加GPU和Framebuffer显示设备

1. 概述 上一章节我们已经成功的移植完busybox,到此,我们已经把我们Naruto-Pi的基本功能全部实现了,接下来,我们会不断探索,引入一些高级驱动,哇咔咔,真厉害,本章节比较简单,我们使用之前我们的8组virtio,我们就用其中一组模拟GPU,由于GPU我没深入了解过,所以我们…

[FFmpeg学习]初级的SDL播放mp4测试

在之前的学习中&#xff0c;通过AVFrame来保存为图片来认识了AVFrame&#xff0c; [FFmpeg学习]从视频中获取图片_ffmpeg 获取图片-CSDN博客 在获取到AVFrame时&#xff0c;还可以调用SDL方法来进行展现&#xff0c;实现播放效果。 参考资料 SDL&#xff0c;ffmpeg实现简单…

MySQL中的数据库约束

目录 导读&#xff1a; 约束类型 1、not null&#xff08;不能为空&#xff09; 2、unique(唯一) 3、default(默认值约束) 4、primary key(唯一)与unique 相同点&#xff1a; 不同点&#xff1a; auto_increment&#xff1a; 5、foreign key(外键) 语法形式&#xff…

康姿百德集团公司官网床垫价格透明,品质睡眠触手可及

选择康姿百德床垫&#xff0c;价格透明品质靠谱&#xff0c;让你拥有美梦连连 在当今社会&#xff0c;良好的睡眠质量被越来越多的人所重视。睡眠不仅关系到我们第二天的精力状态&#xff0c;更长远地影响着我们的身体健康。因此&#xff0c;选择一款合适的床垫对于获得优质睡…