手把手教你使用npm和vite 2.0创建vue项目(非ts),配置打包环境

Vite 需要node版本 >= 12.0.0,使用 node --version 查看当前node版本,过低的话需要去官网下载更高的可用版本。

1、创建项目:使用npm,yarn的同学可以去官网查看此步骤

使用 npm --version 查看npm版本,然后创建项目:

# npm 6.x
npm init @vitejs/app my-vue-app --template vue

# npm 7+, 需要额外的双横线:
npm init @vitejs/app my-vue-app -- --template vue

然后按指引进入项目目录

2、配置路由:

安装

npm install vue-router@4 --save

代码:在src下新建router/index.js,并创建views/home.vue和login.vue具体视项目需要。

import { createRouter, createWebHashHistory } from 'vue-router'
const routes = [
  {
    path: '/',
    name: 'Home',
    meta: {
      title: '首页'
    },
    component: () => import('../views/home.vue'),
  },
  {
    path: '/login',
    name: 'Login',
    meta: {
      title: '登录'
    },
    component: () => import('../views/login.vue'),
  },
]
const router = createRouter({
  history: createWebHashHistory(),
  routes
})
export default router

3、配置网络请求

安装

npm i axios --save

代码:在src下新建api/http.js。

import axios from 'axios'
const baseURL = import.meta.env.VITE_APP_WEB_URL

const service = axios.create({
  baseURL,
  timeout: 5000 // request timeout
});
// 发起请求之前的拦截器
service.interceptors.request.use(
  config => {
    // 如果有token 就携带tokon
    const token = window.localStorage.getItem('authorization')
    if (token) {
      config.headers.common.Authorization = token
    }
    return config
  },
  error => Promise.reject(error)
);
// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data

    if (response.status !== 200) {
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    return Promise.reject(error)
  }
)
export default service

在src下新建index.js,可把接口统一写在此处。

import http from './http.js'

let api = {}

// 登录
api.login = ({ userName, password, captcha }) => {
  return http.post('api/xxxxxx', { userName, password, captcha })
}

// 获取用户信息
api.getUserInfo = () => {
  return http.get('api/xxxxxxxxxx')
}

export default api

配置开发及打包环境

根目录下新建.env.development

NODE_ENV=development
  
VITE_APP_WEB_URL='http://localhost:6078/' // 本地调试

.env.testing

NODE_ENV=testing
  
VITE_APP_WEB_URL='http://test-api.xxxxx.com/' // 测试环境

.env.production

NODE_ENV=production
  
VITE_APP_WEB_URL='https://api.xxxxx.com/' // 生产环境

package.json中添加后面两行,打包时执行命令:npm run build--test,生产环境:npm run build--prod

"scripts": {
    "dev": "vite",
    "build": "vite build",
    "serve": "vite preview",
    "build--test": "vite build --mode testing",
    "build--prod": "vite build --mode production"
},

如果需要配置代理,可修改vite.config.js

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
const path = require('path')
const resolve = dir => path.join(__dirname, dir)

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    // 文件系统路径的别名
    alias:{
      '@': resolve('src')
    }
  },
  server: {
    // 配置代理
    proxy: {
      // 简写配置
      '/api/': 'http://XXX:4567/api/',
      // 完整配置
      '/test/': {
        target: 'http://XXX:6532/test/',
        changeOrigin: true,
        pathRewrite: {
          '^/test/': ''
        }
      }
    }
  }
})

在main.js中挂载

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import api from './api'

const app = createApp(App);
app.config.globalProperties.$api = api
app.use(router)
.use(api)
.mount('#app')

组件中调用接口

async getUserInfo () {
  try {
    const userResponse= await this.$api.getUseInfo()
    this.userInfo = userResponse.data
  } catch (err) {
    console.log('err', err)
  }
}

至此,完成项目的创建和打包环境配置,如果需要使用vuex、vant等,可参考文中示例。如有疑问欢迎探讨。如果本文对你有些许帮助,动动手指点个赞吧,你的鼓励是我创作的动力,笔芯


补充

使用eslint:

安装

npm install --save-dev @typescript-eslint/eslint-plugin @vue/eslint-config-standard @vue/eslint-config-typescript eslint eslint-plugin-import eslint-plugin-node eslint-plugin-promise eslint-plugin-vue

代码:根目录下新建.eslintrc.js

module.exports = {
    root: true,
    env: {
      node: true
    },
    extends: [
      'plugin:vue/vue3-essential',
      '@vue/standard'
    ],
    parserOptions: {
      ecmaVersion: 2020
    },
    rules: {
      'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
      'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
      '@typescript-eslint/ban-ts-ignore': 'off',
      '@typescript-eslint/no-var-requires': 'off',
      '@typescript-eslint/no-empty-function': 'off',
      '@typescript-eslint/no-unused-vars': 'off',
      '@typescript-eslint/ban-ts-comment': 'off',
      '@typescript-eslint/no-explicit-any': 'off'
    }
}

package.json中添加:"lint:code": "eslint --fix src/**/*.{js,ts,tsx,vue}",

"scripts": {
    "dev": "vite",
    "build": "vite build",
    "serve": "vite preview",
    "lint:code": "eslint --fix src/**/*.{js,ts,tsx,vue}",
    "build--test": "vite build --mode testing",
    "build--prod": "vite build --mode production"
},

命令行执行:npm run lint:code即可自行按照配置修复代码。

*vite真的快,确实如官网所说:

一旦你体验到 Vite 有多快,我们十分怀疑你是否愿意再忍受像曾经那样使用打包器开发。

  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无敌无敌小可爱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值