本次使用的基础框架是由vue3+elementUl配合使用
前置工作安装nvm与使用nvm安装vue
参考文章
window下安装并使用nvm : https://blog.csdn.net/HuangsTing/article/details/113857145
安装vue与vue3: https://blog.csdn.net/weixin_69553582/article/details/129584587
使用安装好的vue脚手架cli进行项目生成
1、首先使用管理员权限打开cmd 然后开始创建项目

2、 开始创建项目
?Please pick a preset: (Use arrow keys)
> Default ([Vue 3] babel, eslint) // 默认的vue3模板
Default ([Vue 2] babel, eslint) // 默认的vue2版本
Manually select features // 手动选择需要的功能生成模板
前面两个是内置模板,可以直接创建好项目,这边为了展示过程就选第三个自定义选项
3、选择项目所需配置
Vue CLI v5.0.8?Please pick a preset:Manually select features
?Check the features needed for your project:(Press<space>toselect,<a>totoggle all,<i>toinvert selection, and
<enter>toproceed)(*)Babel(*)TypeScript()ProgressiveWebApp(PWA)Support(*)Router>(*)Vuex(*) CSS Pre-processors
(*)Linter/Formatter()UnitTesting() E2E Testing
选中的每一项后面基本都有相关的设置,空格键切换选定及取消:
Babel // 使用 babel
TypeScript // TypeScript可以根据项目需要去配置 Progressive
Web App (PWA) Support // 一般项目我们都不使用PWA Router //
建议添加vue-router,官方的路由管理包,添加之后也会自动生成路由配置相关代码 Vuex // 建议添加vuex,官方的全局状态管理包,添加之后也会自动生成全局状态配置相关代码
CSS Pre-processors //使用css预处理器,建议勾选,因为一般我们会使用scss或者less Linter / Formatter // 代码格式化相关配置
Unit Testing // 不配置测试
E2E Testing // 不配置测试
选择项目版本
Vue CLI v5.0.8?Please pick a preset:Manually select features
?Check the features needed for your project:Babel, TS,Router,Vuex, CSS Pre-processors,Linter?Choose a version of Vue.js that you want tostart the project with(Use arrow keys)>3.x
2.x
这次是vue3
是否使用Class风格装饰器?
? Choose a version of Vue.js that you want to start the project with 3.x
? Use class-style component syntax? (y/N) n
即原本是:home = new Vue()创建vue实例
使用装饰器后:class home extends Vue{}
一般直接选n了,旧的看久了也习惯了
是否使用TypeScript和Babel的形式编译 JSX.
? Use Babel alongside TypeScript (required for modern mode, auto-detected polyfills, transpiling JSX)? (Y/n) n
由于之前选择了TypeScript,所以这里询问:是否使用TypeScript和Babel的形式编译 JSX,根据个人爱好,这边选n
路由使用历史模式?
? Use history mode for router? (Requires proper server setup for index fallback in production)(Y/n) y
这种模式充分利用 history.pushState API 来完成 URL 跳转而无须重新加载页面
使用什么css预编译器
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): (Use arrow keys)> Sass/SCSS (with dart-sass)
Less
Stylus
默认提供了sass、less、及Stylus三中预处理,一般情况下我们都是使用sass,这边选 scss
代码格式化相关配置
? Pick a linter / formatter config: (Use arrow keys)> ESLint with error prevention only
ESLint + Airbnb config
ESLint + Standard config
ESLint + Prettier
ESLint with error prevention only: 只进行报错提醒;
ESLint + Airbnb config: 不严谨模式;
ESLint + Standard config: 正常模式;
ESLint + Prettier:严格模式;
在什么情况下,进行代码格式化检查修复
? Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection, and <enter> to
proceed)>(*) Lint on save
() Lint and fix on commit
Lint on save :保存文件是格式化代码
Lint and fix on commit:git提交代码的时候格式化
配置保存在那里
? Where do you prefer placing config for Babel, ESLint, etc.? (Use arrow keys)
In dedicated config files
> In package.json
In dedicated config files:单独的文件
In package.json:存储在package.json文件中
是否保存配置,应用在将来项目
? Save this as a preset for future projects? (y/N) n
根据自己需求定,这里就不保存了
选择安装包管理工具
? Pick the package manager to use when installing dependencies:
Use Yarn
> Use NPM
这里用的是npm
目录结构
搭建完成的样子,这个是比较初始的版本
生成后会有一些常用的配置文件比如 .env.development,.env.production,.gitignore等手动添加
common-back
├── node_modules/ ————存放项目的所有依赖包,由 npm 或 yarn 自动生成和管理
├── public ————静态文件目录,里面的文件不会被 Webpack 处理,最终会原样复制到打包目录下
│ ├── favicon.ico #网站的图标
│ └── index.html #应用的主 HTML 文件,Vue CLI 会在构建时自动注入生成的静态资源链接
├── src ————源代码目录,存放应用的主要代码
│ ├── assets #存放静态资源,如图像、字体等。这些文件会由 Webpack 处理,可以通过相对路径引用
│ │ └── logo.png(示例)
│ ├── components #存放 Vue 组件,每个组件都是一个独立的 .vue 文件
│ │ └── HelloWorld.vue(示例)
│ ├── router #存放路由配置文件
│ │ └── index.ts(示例)
│ ├── store # Vuex 状态管理目录,用于集中管理组件状态和数据流
│ │ └── index.ts(示例)
│ ├── views #存放视图组件,通常对应路由,每个视图都是一个独立的 .vue 文件
│ │ ├── AboutView.vue(示例主页调用组件)
│ │ └── HomeView.vue(默认生成的主页组件)
│ ├── App.vue #应用程序根组件,整个应用的入口点,通常包含路由视图和其他全局共享组件
│ ├── main.ts #应用程序入口脚本,用于初始化Vue实例、引入并配置路由、状态管理等核心模块
│ └── shims-vue.d.ts #TypeScript 类型声明文件,为Vue相关API提供类型支持
├── README.md ————项目文档和说明文件,介绍项目结构、启动方式及注意事项等
├── package-lock.json ————npm 包管理器中用于锁定项目依赖版本的文件
├── package.json ————npm 包配置文件,包括项目依赖、脚本命令、项目信息等元数据
├── vue.config.js ————一些打包的特殊设置
├── .env.development ————**测试环境配置**
├── .env.production ————**生产环境配置**
├── .gitignore ———— **git忽略文件**
└── tsconfig.json ————TypeScript 项目的核心配置文件,用于指定编译选项、包含的源文件、排除的文件等信息
例如(本示例是基于cli来构建.env)文件:
NODE_ENV ='development' //模式
VUE_APP_MODE ='development' //通过"VUE_APP_MODE"变量来区分环境
VUE_APP_API_URL ='http://127.0.0.1:8126/api/' //api地址
对应的package.json 中的配置:
- 注:vue3 serve启动就默认加载development环境,build默认加载production环境
"scripts":{"serve":"vue-cli-service serve --mode development","build":"vue-cli-service build --mode production","lint":"vue-cli-service lint"},
同时,创建项目完成后你会发现,现在项目的文件有所不同,会发现相比于vue2少了build与config文件夹,所以vue3提供了一个可选的配置文件 ——vue.config.js。
const path =require('path');//模块热替换(HMR - hot module replacement)功能会在应用程序运行过程中,替换、添加或删除 模块,而无需重新加载整个页面const HotHashWebpackPlugin =require('hot-hash-webpack-plugin');constresolve=(dir)=> path.join(__dirname,'.', dir);
module.exports ={//是否生成源码映射文件,生产环境是禁止的,主要调试时候使用
productionSourceMap:false,// 通常用于确定在开发环境还是生产环境//publicPath: process.env.NODE_ENV === 'production'? '': '/',// 打包文件输出目录, 默认打包到dist文件下
outputDir:'dist',// 放置静态资源
assetsDir:'static',//所有 webpack-dev-server 的选项都支持。注//可以是一个指向开发环境 API 服务器的字符串
devServer:{
port:8012,// 端口号
host:'127.0.0.1',
https:false,// https:{type:Boolean}配置前缀
open:true,//配置自动启动浏览器// 服务器代理,解决开发环境下跨域问题/* proxy: {
// 一旦devserver(5000)服务器接收到 /api/xxx的请求,就会把请求转发到另外一个服务器(3000)
'/api': {
target: 'http://localhost:3000',
// 是否允许跨域
changeOrigin: true,
secure: false, // 如果是https接口,需要配置这个参数
ws: true, //如果要代理 websockets,配置这个参数
// 发送请求时,请求路径重写:将/api/xxx -> /xxx(去掉/api)
pathRewrite: {
'^/api': ''
}
}
}*/},
pluginOptions:{"style-resources-loader":{
preProcessor:"scss",
patterns:[],},},//是一个函数,会接收一个基于 webpack-chain 的 ChainableConfig 实例。// 允许对内部的 webpack 配置进行更细粒度的修改chainWebpack:(config)=>{// 添加全局scss文件const types =['vue-modules','vue','normal-modules','normal'];//匹配到所有需要导入的文件
types.forEach(type=>{let rule = config.module.rule('scss').oneOf(type)
rule.use('sass-resources-loader').loader('style-resources-loader').options({
patterns:[
path.resolve(__dirname,'src/css/base.scss')]}).end();});//配置import 和 require 等路径别名
config.resolve.alias
.set('@',resolve('src')).set('api',resolve('src/apis')).set('common',resolve('src/common'))//配置图片的打包规则//添加新规则
config.module.rule('images').test(/\.(jpg|png|gif)$/).set('parser',{
dataUrlCondition:{
maxSize:10*1024// 10KiB}})// 添加svg-sprite-loader//添加svg-sprite-loader的目的是为了将svg图片转换为svg标签插入html
config.module.rule('svg').test(/.svg$/).include.add(resolve('src/svg')).end().use('svg-sprite-loader').loader('svg-sprite-loader');//插件plugins 的配置 构建期间自动检测环境变化 要先安装 cross-env/* config.plugin('define').tap(args => [{
args[0].API_CONFIG = JSON.stringify(apiConfig[process.env.NODE_ENV])
return args
}]);*/// 生产环境配置if(process.env.NODE_ENV==='production'){
config.output.filename('./js/[name].[chunkhash:8].js');
config.output.chunkFilename('./js/[name].[chunkhash:8].js');
config.plugin('extract-css').tap(args=>[{
filename:'css/[name].[contenthash:8].css',
chunkFilename:'css/[name].[contenthash:8].css'}]);
config.plugin('hotHash').use(HotHashWebpackPlugin,[{ version :'1.0.0'}]);
config.optimization.minimize(true).minimizer('terser').tap(args=>{let{ terserOptions }= args[0];
terserOptions.compress.drop_console =true;
terserOptions.compress.drop_debugger =true;return args
});
config.optimization.splitChunks({
cacheGroups:{
common:{
name:'common',
chunks:'all',
minSize:1,
minChunks:2,
priority:1},
vendor:{
name:'chunk-libs',
chunks:'all',
test:/[\/]node_modules[\/]/,
priority:10}}});}}};
运行
使用webstorm打开后就是这个这个样子
点击 npm run serve 如果没有配置vue.config.js 就可以看见它在运行了
最后点击下方
Local: http://localhost:8080/
就可以在浏览器上运行了
同时可以在main.ts中打印env的内容:
import{ createApp }from'vue'import App from'./App.vue'import router from'./router'import store from'./store'createApp(App).use(store).use(router).mount('#app')
console.log(process.env.VUE_APP_API_URL)
console.log(process.env.NODE_ENV)
可以看到打印结果是这样的

版权归原作者 红烧栗子黄瓜鱼 所有, 如有侵权,请联系我们删除。