vue3.0 vite + typeScript + axios + element-plus + eslint项目搭建

1.项目初始化

npm init vite demo-b

选择vue + vue-ts
在这里插入图片描述在这里插入图片描述
2. eslint 初始化

npx eslint --init
第一步
? How would you like to use ESLint? ...   // eslint检查方式
  To check syntax only   // 只检查语法
> To check syntax and find problems  // 检查语法并查找问题
  To check syntax, find problems, and enforce code style  // 检查语法、查找问题并强制执行代码样式
第二步
? What type of modules does your project use? ...  // 使用模块类型
> JavaScript modules (import/export)  // JavaScript模块(导入/导出)
  CommonJS (require/exports)  // CommonJS(需要/导出)
  None of these  // 这些都不是
第三步
? Which framework does your project use? ... 
  React
> Vue.js
  None of these
第四步
? Does your project use TypeScript? » Yes  // 项目是否使用TypeScript
第五步
? Where does your code run? ...  (Press <space> to select, <a> to toggle all, <i> to invert selection)  // 执行方式 (全选)
√ Browser  // 浏览器
√ Node  // node
第六步
? What format do you want your config file to be in? ...   // 配置文件格式
> JavaScript
  YAML
  JSON
第七步
? Would you like to install them now with npm? »  Yes  // 是否使用npm安装

npm安装完成后生成 .eslintrc.js配置文件

// npx eslint --init  eslint 初始化
module.exports = {
    "env": {
        "browser": true,
        "es2021": true,
        "node": true
    },
    "extends": [
        "eslint:recommended",
        "plugin:vue/essential",
        "plugin:@typescript-eslint/recommended"
    ],
    "parserOptions": {
        "ecmaVersion": 12,
        "parser": "@typescript-eslint/parser",
        "sourceType": "module"
    },
    "plugins": [
        "vue",
        "@typescript-eslint"
    ],
    "rules": {
      // '@typescript-eslint/ban-ts-ignore': 'off',
      // '@typescript-eslint/explicit-function-return-type': 'off',
      '@typescript-eslint/no-explicit-any': 'off',  // any是否检查
      // '@typescript-eslint/no-var-requires': 'off',
      // '@typescript-eslint/no-empty-function': 'off',
      // '@typescript-eslint/no-use-before-define': 'off',
      // '@typescript-eslint/ban-ts-comment': 'off',
      // '@typescript-eslint/ban-types': 'off',
      // '@typescript-eslint/no-non-null-assertion': 'off',
      // '@typescript-eslint/explicit-module-boundary-types': 'off',
      // '@typescript-eslint/no-unused-vars': [
      //   'error',
      //   {
      //     argsIgnorePattern: '^h$',
      //     varsIgnorePattern: '^h$'
      //   }
      // ],
      // 'no-unused-vars': [
      //   'error',
      //   {
      //     argsIgnorePattern: '^h$',
      //     varsIgnorePattern: '^h$'
      //   }
      // ],
      // 'space-before-function-paren': 'off',
      // quotes: ['error', 'single'],
      // 'comma-dangle': ['error', 'never'],
      // 'vue/require-default-prop': 'off',
      // 'vue/custom-event-name-casing': 'off',
      // 'no-use-before-define': 'off',
      // 'vue/comment-directive': 'off',
      // 'vue/singleline-html-element-content-newline': 'off',
      // 'vue/html-self-closing': 'off',
      // 'vue/max-attributes-per-line': 'off'
    }
};
  

3.0 package.json 配置

"scripts": {
    "dev": "vite --mode dev", // 开发
    "build": "vue-tsc --noEmit && vite build",
    "serve": "vite preview",
    "build:test": "vue-tsc --noEmit && vite build --mode test",  // 自定义打包命令 测试
    "build:pro": "vue-tsc --noEmit && vite build --mode pro" // 生产
  },

在与src同级创建文件 .env.dev .env.test .env.pro 环境配置文件
在这里插入图片描述
.env文件配置:

NODE_ENV = 'development' // 环境
VITE_APP_TITLE = '开发' // 环境名称  以VITE_APP_  开头后面名称自定义
VITE_APP_API = ''

安装依赖 根据需求 选择安装在开发环境devDependencies和生产打环境dependencies

"dependencies": {
    "axios": "^0.21.1",
    "element-plus": "^1.0.2-beta.70",
    "qs": "^6.10.1",
    "vue": "^3.2.2",
    "vue-router": "^4.0.11",
    "vuex": "^4.0.2"
  },
  "devDependencies": {
    "@types/node": "^16.6.2",
    "@types/qs": "^6.9.7",
    "node-sass": "^6.0.1",
    "sass": "^1.38.0",
    "sass-loader": "^12.1.0",
    "style-loader": "^3.2.1",
    "vite-plugin-compression": "^0.3.5",
    "vite-plugin-style-import": "^1.1.1",
    // 以下初始化时以安装
    "@typescript-eslint/eslint-plugin": "^4.29.3",
    "@typescript-eslint/parser": "^4.29.3",
    "@vitejs/plugin-vue": "^1.3.0",
    "@vue/compiler-sfc": "^3.0.5",
    "eslint": "^7.32.0",
    "eslint-plugin-vue": "^7.16.0",
    "typescript": "^4.3.2",
    "vite": "^2.4.4",
    "vue-tsc": "^0.2.2"
  }

其中element-plus 根据官方文档进行安装配置

配置文件tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "moduleResolution": "node",
    "strict": true,
    "jsx": "preserve",
    "sourceMap": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "lib": ["esnext", "dom"],
    "baseUrl": "./",
    "paths":{ // vite中@指向需要在vite.config.ts和tsconfig.json共同配置
      "@": ["src"],
      "@/*": ["src/*"],
    }
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}

配置文件vite.config.ts

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import styleImport from 'vite-plugin-style-import'
import viteCompression from 'vite-plugin-compression'
// 如果编辑器提示 path 模块找不到,则可以安装一下 @types/node -> npm i @types/node -D
import { resolve } from 'path' // 主要用于alias文件路径别名

// https://vitejs.dev/config/
export default defineConfig({
  base: './', // 设置打包路径
  resolve: { // 配置文件别名 vite1.0是/@/  2.0改为/@ 这里是将src目录配置别名为 @ 方便在项目中导入src目录下的文件 tsconfig 中的paths也需要配置
    alias: {
      '@': resolve(__dirname, "src"),
    }
  },
  plugins: [
    vue(),  // 配置需要使用的插件列表,这里将vue添加进去
    styleImport({
      libs: [{
        libraryName: 'element-plus',
        esModule: true,
        ensureStyleFile: true,
        resolveStyle: (name) => {
          name.slice(3)
          return `element-plus/packages/theme-chalk/src/${name}.scss`;
        },
        resolveComponent: (name) => {
          return `element-plus/lib/${name}`;
        }
      }]
    }),
    viteCompression({ //生成压缩包gz
      verbose: true,
      disable: false,
      threshold: 10240,
      algorithm: 'gzip',
      ext: '.gz',
    })
  ],
  css: {
    preprocessorOptions: {
      sass: {
        modifyVars: {
          // 'primary-color': '#52c41a',
          // 'link-color': '#1DA57A',
          // 'border-radius-base': '2px',
        },
        javascriptEnabled: true,
      },
    },
  },
  // 强制预构建插件包
  optimizeDeps: {
    include: [
      'element-plus',
      'element-plus/lib/locale/lang/zh-cn'
    ]
  },
  // 打包配置
  build: {
    target: 'modules',
    outDir: 'dist', //指定输出路径
    assetsDir: 'assets', // 指定生成静态资源的存放路径
    minify: 'terser', // 混淆器,terser构建后文件体积更小
    terserOptions: { // 去除console
      compress: {
        drop_console: true,
        drop_debugger: true
      }
    }
  },
  // 本地运行配置,及反向代理配置
  server: {
    host: 'localhost',
    port: 3000, // 设置服务启动端口号
    https: false, // 是否开启 https
    cors: true, // 默认启用并允许任何源
    open: false, // 在服务器启动时自动在浏览器中打开
    proxy: { //反向代理配置,注意rewrite写法,开始没看文档在这里踩了坑
      '/api': {
          // target: 'http://192.168.99.223:3000',   //代理接口
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  },
})

路由文件router.ts

import { createRouter, createWebHashHistory } from "vue-router";

const constantRouterMap: Array<any> = [
  {
    path: '/',
    name: '',
    redirect: '/index',
    component: () => import(/* webpackChunkName: "group-A" */ '../views/home/index.vue'),
    meta: {},
    children:[]
  }
]
const router = createRouter({
  history: createWebHashHistory(),
  routes: [...constantRouterMap]
})

export default router

vuex store index.ts 文件

import { createStore } from "vuex";
import getters from './getters'

const store = createStore({
  state: {},
  getters,
  mutations: {},
  actions: {},
  modules: {}
})
export default store

app.vue 根组件中配置 vuex store 刷新本地保存

<script lang="ts">
import { defineComponent } from 'vue'
import store from './store'
export default defineComponent({
  name: 'App',
  setup() {
    console.log(import.meta.env)  // 读取当前环境信息
    // 在页面加载时读取sessionStorage
    const storeList: any = sessionStorage.getItem('store')
    if (storeList) {
      store.replaceState(
        Object.assign(
          {},
          store.state,
          JSON.parse(storeList)
        )
      )
    }
    // 在页面刷新时将vuex里的信息保存到sessionStorage里
    // beforeunload事件在页面刷新时先触发
    window.addEventListener('beforeunload', () => {
      sessionStorage.setItem('store', JSON.stringify(store.state))
    })
  }
})
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值