vue-cli3構建ts項目


1、構建項目

vue create xxx

上面的第一條,也就是 aaa 這一個選項在你第一次創建項目的時候是並不會出現的,只有你第一次創建完成項目后回提示你保存為默認配置模板,下次新建項目的時候就可以使用你選用的配置快速新建項目了,不需要再重新選擇配置項目了。

第二條選項便是 vue cli 3 默認的項目模板,包含 babel 和 eslint。

第三條選項便是自主選擇你項目所需的配置。

這里由於默認模板沒有啥展示的必要所以我們便選擇手動配置。

選擇項目配置:

這里我們可以選擇我們需要的配置選項,選擇完成后回車進入下一步。

在選擇功能后,會詢問更細節的配置

 

TypeScript:

  1. 是否使用class風格的組件語法:Use class-style component syntax?

  2. 是否使用babel做轉義:Use Babel alongside TypeScript for auto-detected polyfills?

Router:

  1.是否使用history模式:Use history mode for router?

CSS Pre-processors:

  1. 選擇CSS 預處理類型:Pick a CSS pre-processor

Linter / Formatter

  1. 選擇Linter / Formatter規范類型:Pick a linter / formatter config

  2. 選擇lint方式,保存時檢查/提交時檢查:Pick additional lint features

Testing

  1. 選擇Unit測試方式

  2. 選擇E2E測試方式

選擇 Babel, PostCSS, ESLint 等自定義配置的存放位置 Where do you prefer placing config for Babel, PostCSS, ESLint, etc.?

 

創建成功。

2、修改配置

 vue-cli3腳手架生成項目目錄說明

│  .browserslistrc
│  .gitignore
│  .postcssrc.js // postcss 配置
│  babel.config.js
│  package.json // 依賴
│  README.md // 項目 readme
│  tsconfig.json // ts 配置
│  tslint.json // tslint 配置
│  vue.config.js // webpack 配置(~自己新建~)
│  yarn.lock
│  
├─public // 靜態頁面
│  │—favicon.ico
│  │—index.html
│ 
├─src // 主目錄
│  ├─assets // 靜態資源
│  │      logo.png
│  │  
│  ├─components
│  │      HelloWorld.vue
│  │ 
│  │─views // 頁面
│  │      About.vue
│  │      Home.vue
│  │ 
│  │  App.vue // 頁面主入口
│  │ 
│  │  main.ts // 腳本主入口
│  │ 
│  ├─router // 路由配置
│  │      index.ts
│  │  
│  │  registerServiceWorker.ts // PWA 配置
│  │ 
│  │  shims-tsx.d.ts
│  │  shims-vue.d.ts
│  │         
│  │  
│  ├─store // vuex 配置
│  │      index.ts
│  │      
│  ├─typings // 全局注入(~自己新建~)
│  │  
│  ├─utils // 工具方法(axios封裝,全局方法等)(~自己新建~)
│  
│          
└─tests // 測試用例
    ├─e2e
    │  ├─plugins
    │  │      index.js
    │  │      
    │  ├─specs
    │  │      test.js
    │  │      
    │  └─support
    │          commands.js
    │          index.js
    │          
    └─unit
            HelloWorld.spec.ts        

1、在.browserslistrc文件中添加

last 3 ie versions,
not ie <= 8

其它配置,請去https://github.com/browserslist/browserslist。npx browserslist在項目目錄中運行以查看查詢選擇了哪些瀏覽器

2、tslint配置

// 關閉console
"no-console": [true, "log", "dir", "table"]
    
// tslint的函數前后空格:
"space-before-function-paren": ["error", {
  "anonymous": "always",
  "named": "always",
  "asyncArrow": "always"
}]


// tslint分號的配置:
"semicolon": [true, "never"]

其它規則:https://palantir.github.io/tslint/rules/

3、路由處理邏輯(登錄驗證、攔截等)

// main.ts文件

router.beforeEach((to: any, from: any, next: any) => {
  if (to.name === 'login') {
    next({name: 'home/index'})
  } else {
    next()
  }
})

4、axios改造

npm i axios --save

src下新建axios.d.ts axios.config.ts文件

//axios.config.ts
import axios, { AxiosInstance } from 'axios' declare module 'Vue/types/vue' { interface Vue { $axios: AxiosInstance } }
// main.ts文件
import Vue from 'vue';
import axios from 'axios';

Vue.prototype.$axios = axios;

/**
* 創建 axios 實例
*/
const service = axios.create({
timeout: 3000,
baseURL: 'http://xxx',
});

/**
* req 攔截器
*/
service.interceptors.request.use((config: object): object => {
return config
}, (error: any): object => {
return Promise.reject(error)
});

/**
* res 攔截器
*/
service.interceptors.response.use((response: any) => {
const res = response.data;
if (res.error) {
if (process.env.NODE_ENV !== 'production') {
console.error(res);
}
return Promise.reject(res);
}
return Promise.resolve(res);
});
// main.ts
import './axios.config';

4、store改造

├── index.html
├── main.js
├── components
│   ├── App.vue
│   └── ...
└── store
    ├── index.ts          # 我們組裝模塊並導出 store 的地方
    ├── actions.ts        # 根級別的 action
    ├── mutations.ts      # 根級別的 mutation
    └── modules
        ├── cart.ts      # 購物車模塊

 

使用:

  • 使用module形式
  • 全局的一些操作,方法,放入store中,業務邏輯盡量少放,項目全局方法可以放入。例如:cookieglobal cache

  action(異步): api的操作, 調用方式:this.$store.dispatch(functionName, data)

  mutations(同步): dom相關操作,方法名一般使用常量,
  調用方式: this.$store.commit(mutationsName, data)

  this.$store.getters[XXX] => this.$store.getters[namespaced/XXX]
  this.$store.dispatch(XXX, {}) => this.$store.dispatch(namespaced/XXX, {})
  this.$store.commit(XXX, {}) => this.$store.commit(namespaced/XXX, {})
//store/index.ts
import Vue from 'vue';
import Vuex from 'vuex';
import cart from './modules/cart';

Vue.use(Vuex);

export default new Vuex.Store({
  modules: {
    cart,
  },
});
// cart.ts
import {ActionContext} from 'vuex';
export interface State {
    token: string;
}

const state: State = {
    token: '',
};

// getters
const getters = {
    toUpperToken: (state: State) => {
        return state.token.toUpperCase();
    },
};

// actions
const actions = {
    setTokenAsync({ commit }: ActionContext<State, State>, payload: any) {
        setTimeout(() => {
            commit('setToken', payload);
        }, 1000);
    },
};

// mutations
const mutations = {
    setToken(state: State, payload: any) {
        state.token = payload;
    },
};

export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations,
};

5、vue.config.js配置

  https://cli.vuejs.org/zh/config/#vue-config-js所列出的屬性,可以直接配置。其它屬性可以通過configureWebpackchainWebpack配置。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM