【Vue】VueCli项目创建说明

2,251 阅读5分钟

Vue3.0虽然优秀;但生态环境还不成熟,我们生产中遇到的许多问题还无法解决。因此本教程以Vue2.0为准。 写这句话还是三年前的事情了,如今可以大胆地来使用vue3.

创建项目

基于全局安装了@vue/cli的方式创建

先全局安装@vue/cli

npm install -g @vue/cli
# OR
yarn global add @vue/cli

假设项目名为example,创建项目。

vue create example

基于npx

npx作为npm5.2版本之后的命令,也是npm exec的缩写,这种形式我们称之为语法糖。使用npx则可以不用手动安装@vue/cli

npx @vue/cli create example
# OR
npm exec @vue/cli create example

@vue/cli选项说明

方向键操作,Enter键选择Manually select features

❯ Default ([Vue 2] babel, eslint)
  Default (Vue 3 Preview) ([Vue 3] babel, eslint)
  Manually select features

方向键操作,空格键选择;选择完后,按Enter键进行下一步。

选择标准如下:

? Check the features needed for your project:
 ◉ Choose Vue version
 ◉ Babel
 ◉ TypeScript
 ◯ Progressive Web App (PWA) Support
 ◉ Router
 ◉ Vuex
 ◉ CSS Pre-processors
 ◉ Linter / Formatter
 ◉ Unit Testing
 ◉ E2E Testing

插件用途说明:

插件说明
Choose Vue version选择Vue
BabelJavaScript编译器(选择ES6语法)
RouterVue路由
VuexVue数据仓库
CSS Pre-processors动态css(如scss)
Linter / Formatter代码风格标准
Unit Testing单元测试
E2E TestingE2E测试

Unit TestingE2E Testing不在开发阶段一使用,如果开发时间足够则启用测试。

控制台选择Vue3.x版本,按Enter键进行下一步:

? Choose a version of Vue.js that you want to start the project with (Use arrow keys)
  2.x
❯ 3.x

不再推荐在 Vue 3 中使用基于类的组件,这可是官方自己说的:

Use class-style component syntax? (y/N) N

将Babel与TypeScript一起使用(现代模式需要,自动检测多填充,传输JSX):

Use Babel alongside TypeScript (required for modern mode, auto-detected polyfills, transpiling JSX)? Y

不采用Vue Router的history模式,因为本项目不进行多余的配置。

输入n,按Enter键进行下一步:

Use history mode for router? (Requires proper server setup for index fallback in production) (Y/n) n

动态css选择Sass/SCSS (with dart-sass)(默认),这是当前最受欢迎也是最好的一款动态css编译器。

直接按Enter键进行下一步:

? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): (Use arrow keys)
❯ Sass/SCSS (with dart-sass)
  Less
  Stylus

代码风格选择ESLint with error prevention only(默认)。因为当你编写的代码不符合标准的开发风格时,报错才能在开发阶段解决问题。

选择standardairbnbprettier可自己去了解,本文以标准standard作为示例:

Pick a linter / formatter config: (Use arrow keys)
  ESLint with error prevention only
  ESLint + Airbnb config
❯ ESLint + Standard config
  ESLint + Prettier

选择在保存时进行风格检查(默认),直接按Enter键进行下一步:

Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection)
❯◉ Lint on save
 ◯ Lint and fix on commit

单元测试插件选择默认的,默认的即是最流行的,直接按Enter键进行下一步:

Pick a unit testing solution: (Use arrow keys)
❯ Jest
  Mocha + Chai

E2E测试插件选择Cypress (Chrome only)(默认,仅谷歌浏览器调试),同样是最流行的,直接按Enter键进行下一步:

Pick an E2E testing solution: (Use arrow keys)
❯ Cypress (Chrome only)
  Nightwatch (WebDriver-based)
  WebdriverIO (WebDriver/DevTools based)

配置文件选择在单独的文件中配置(默认),直接按Enter键进行下一步:

Where do you prefer placing config for Babel, ESLint, etc.? (Use arrow keys)
❯ In dedicated config files
  In package.json

保存当前的选择为一个“future”,这样以后创建项目就不用再次选来选去的了:

输入y同意,然后输入名称为“my-vue3-standard”:

Save this as a preset for future projects? (y/N) y
Save preset as: my-vue3-standard

等待安装完成

加入国际化插件

国际化就是使得项目具备切换各国语言的能力,使用Vue I18n插件创建:

cd example

安装插件的两种方式:

vue add i18n
# or
npx @vue/cli

安装标准:

? The locale of project localization. zh
? The fallback locale of project localization. zh
? The directory where store localization messages of project. It's stored under `src` directory. locales
? Enable locale messages in Single file components ? No

Enable locale messages in Single file components是否在vue文件中使用i18n节点,具体来说就是以下风格

<i18n>
{
  "en": {
    "hello": "hello world!"
  },
  "ja": {
    "hello": "こんにちは、世界!"
  }
}
</i18n>

<template>
  <div id="app">
    <label for="locale">locale</label>
    <select v-model="locale">
      <option>en</option>
      <option>ja</option>
    </select>
    <p>message: {{ $t('hello') }}</p>
  </div>
</template>

<script>
export default {
  name: 'app',
  data () { return { locale: 'en' } },
  watch: {
    locale (val) {
      this.$i18n.locale = val
    }
  }
}
</script>

这种风格比较适合vue3.0,在Vue2.0中我们将国际化配置统一放到一个文件里。

修复TS兼容错误

No overload matches this call.  
Overload 1 of 2, '(options: I18nOptions<{ message: LocaleMessage<VueMessageType>; datetime: DateTimeFormat; number: NumberFormat; }, string, ComposerOptions<{ ...; }, ... 9 more ..., NumberFormats<...>> | VueI18nOptions<...>>, LegacyVueI18n?: any): I18n<...>', gave the following error.  
Type 'LocaleMessages<VueMessageType>' is not assignable to type '{ [x: string]: LocaleMessage<VueMessageType>; }'.  
'string' index signatures are incompatible.  
Type 'VueMessageType' is not assignable to type 'LocaleMessage<VueMessageType>'.  
Type 'string' is not assignable to type 'LocaleMessage<VueMessageType>'.  
Overload 2 of 2, '(options: I18nOptions<{ message: LocaleMessage<VueMessageType>; datetime: DateTimeFormat; number: NumberFormat; }, { messages: "en-US"; datetimeFormats: "en-US"; numberFormats: "en-US"; }, ComposerOptions<...> | VueI18nOptions<...>>, LegacyVueI18n?: any): I18n<...>', gave the following error.  
Property '"en-US"' is missing in type 'LocaleMessages<VueMessageType>' but required in type '{ "en-US": LocaleMessage<VueMessageType>; }'.ts(2769)

按如下方式修改即可:

import { createI18n, LocaleMessages, VueMessageType } from 'vue-i18n'

/**
 * Load locale messages
 *
 * The loaded `JSON` locale messages is pre-compiled by `@intlify/vue-i18n-loader`, which is integrated into `vue-cli-plugin-i18n`.
 * See: https://github.com/intlify/vue-i18n-loader#rocket-i18n-resource-pre-compilation
 */
function loadLocaleMessages (): { [x: string]: LocaleMessages<VueMessageType> } {
  const locales = require.context('./locales', true, /[A-Za-z0-9-_,\s]+\.json$/i)
  const messages: { [x: string]: LocaleMessages<VueMessageType> } = {}
  locales.keys().forEach(key => {
    const matched = key.match(/([A-Za-z0-9-_]+)\./i)
    if (matched && matched.length > 1) {
      const locale = matched[1]
      messages[locale] = locales(key).default
    }
  })
  return messages
}

export default createI18n({
  locale: process.env.VUE_APP_I18N_LOCALE || 'en',
  fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'en',
  messages: loadLocaleMessages()
})

添加element-plus

npx @vue/cli add element-plus

全局引入(Fully import)——懒人之选,或,按需引入(Import on demand)——牛人之选:

? How do you want to import Element Plus?
> Fully import
  Import on demand

是否在Element Plus中使用scss变量,这会对主题设置很有帮助:

Do you want to overwrite the SCSS variables of Element Plus? Y

选择语言中文zh-cn,英文en-us

Choose the locale you want to load, the default locale is English (en) zh-cn

plugins\element.js重命名成element.ts,并进行改造:

import ElementPlus from 'element-plus'
import '../element-variables.scss'
import locale from 'element-plus/lib/locale/lang/zh-cn'
import { App } from '@vue/runtime-dom'

export default (app:App<Element>) => {
  app.use(ElementPlus, { locale })
}