vue cli + typescript搭建项目

163 阅读2分钟

在项目搭建之前建议朋友们可以把npm源设置为国内的淘宝源来加速安装
npm install -g cnpm --registry=https://registry.npm.taobao.org

使用vue脚手架创建项目

  • 如果没有安装 Vue CLI 就先安装 npm install --global @vue/cli

  • 创建一个新工程 vue create my-project

快速创建

default (babel, eslint)

自己选择需要添加的一些功能

? Please pick a preset: Manually select features 
? Check the features needed for your project: Babel Typescript Router Vuex Css Pre-processors Linter / Formatter Unit Testing E2E Testing
? Use class-style component syntax? Yes
? Use Babel alongside TypeScript for auto-detected polyfills? Yes
? Use history mode for router? (Requires proper server setup for index fallback in production) Yes
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Less
? Pick a linter / formatter config: ESLint + Standard config
? Pick additional lint features: Lint on save
? Pick a unit testing solution: Mocha + Chai
? Pick a E2E testing solution: Cypress(Chrome only)
? Where do you prefer placing config for Babel, PostCSS, ESLint, etc.? In package.json
? Save this as a preset for future projects? No

安装一些typescript相关的一些工具

npm i vue-class-component vue-property-decorator --save-dev

添加webpack.config.js

const path = require('path')
module.exports = {
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src')
    }
  }
}

添加tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "noImplicitAny": false,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "resolveJsonModule": true,
    "sourceMap": true,
    "baseUrl": ".",
    "types": [
      "webpack-env",
      "mocha",
      "chai"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "types/**/*.ts",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

添加vue.config.js

const path = require('path')
const resolve = dir => path.join(__dirname, dir)
const BASE_URL = process.env.NODE_ENV === 'production'
  ? '/admin/'
  : '/admin/'
module.exports = {
  publicPath: BASE_URL,
  lintOnSave: true,
  chainWebpack: (config) => {
    config.resolve.alias
      .set('@', resolve('src')) // key,value自行定义,比如.set('@@', resolve('src/components'))
      .set('_c', resolve('src/components'))
  },
  // 设为false打包时不生成.map文件
  productionSourceMap: false,
  // 这里写你调用接口的基础路径,来解决跨域,如果设置了代理,那你本地开发环境的axios的baseUrl要写为 '' ,即空字符串
  // devServer: {
  //   proxy: 'localhost:3000'
  // }

  css: {
    loaderOptions: {
      // 给 sass-loader 传递选项
      less: {
        javascriptEnabled: true
      }
    }
  }
}

添加.eslintrc.js

module.exports = {
  root: true,
  env: {
    node: true
  },
  extends: [
    'plugin:vue/essential',
    '@vue/standard',
    '@vue/typescript'
  ],
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    indent: 'off',
    'object-curly-spacing': 'off',
    'space-before-function-paren': 'off',
    semi: 0,
    'vue/no-parsing-error': [2, {'x-invalid-end-tag': false}],
    'vue/no-unused-vars': 'off',
    'padded-blocks': 'off',
    'vue/order-in-components': 'off',
    'vue/require-default-prop': 'off',
    'vue/attributes-order': 'off',

    'class-methods-use-this': 'off',
    'no-shadow': 'off',
    'prefer-const': 'off',
    'prefer-destructuring': 'off',
    'no-underscore-dangle': 'off',
    'no-restricted-globals': 'off',
    'max-len': 'off',
    'no-param-reassign': 'off',
    'default-case': 'off',
    'no-multi-assign': 'off',
    'no-plusplus': 'off',
    'consistent-return': 'off',
    'import/no-cycle': 'off',
    'import/prefer-default-export': 'off',
    'import/no-unresolved': 'off',
    'no-nested-ternary': 'off',
    'import/extensions': 'off',
    'no-restricted-properties': 'off',
    'vue/order-in-components)': 'off',
    'import/no-extraneous-dependencies': 'off',
    'no-unused-expressions': 'off',
    'array-callback-return': 'off',
    'no-restricted-syntax': 'off',
    'func-names': 'off',
    radix: 'off',
    'no-use-before-define': 'off',
    'no-bitwise': 'off',
    expected: 'off',
    'vue/html-indent': 'off',
    'vue/max-attributes-per-line': 'off',
    'no-return-assign': 'off'
  },
  parserOptions: {
    parser: '@typescript-eslint/parser'
  }
}

添加setting.ts

export const settings = {
  /**
   * @description 配置显示在浏览器标签的title
   */
  title: 'xxx',
  /**
   * @description token在Cookie中存储的天数,默认1天
   */
  cookieExpires: 1,
  /**
   * @description api请求基础路径
   */
  baseUrl: {
    dev: 'xxx',
    pro: 'xxx'
  },
  /**
   * @description 默认打开的首页的路由name值,默认为home
   */
  homeName: 'home'
};

在main.ts中添加配置

/**
 * @description 全局注册应用配置
 */
Vue.prototype.$config = settings;
/**
 * 注册指令
 */
Component.registerHooks([
  'beforeRouteEnter',
  'beforeRouteLeave',
  'beforeRouteUpdate'
]);