The first thing to confirm about the tech stack is:

Vue3.0; Vite2.0; Scaffolding VUE-Router 4.0; Routing Vuex; State management tool element-Plus; Page UI Echart 5.0; Data graphics Axios; Interface node. Js; The back-end mongo; Mysql database; Ts; Language Cloud as JS superset; The serverCopy the code

The second thing is to confirm the project: e-commerce background management system

Construction Project:

1. Vite2.0 + vue3.0

Question 1: Why vite2.0 instead of vue-CLI? Save time to answer

Check the node.js version first, requiring >=12;

Learning vite2.0

Install vite:

NPM: NPM init @vitejs/app Use YARN: yarn create @vitejs/appCopy the code

Step by step, you can create a project directly.

Or create it with the following command:

yarn create vite-app online-management
Copy the code

For example, my project is called online-Management, and I choose VUE framework for development.

Enter the project and install dependencies:

CD online-management NPM run: NPM install yarn run: yarn #Copy the code

Run the project: we can look at the package.json of the project at this point:

NPX vite or NPM run dev or YARN devCopy the code

Just go to http://localhost:3000/

This is a very simple vue3.0+Vite2.0 shelf set up;

2.typescript

It is recommended to use TS to help normalize the code. If you are not familiar with TS, you can continue to use JS.

Install dependencies:

yarn add typescript -D
Copy the code

Configuration tsconfig. Json:

Tsconfig. ts: NPX TSC --initCopy the code

Next, modify:

  1. Change main.js to main.ts;
  2. Modify references in index.html:
  <script type="module" src="/src/main.ts"></script>
Copy the code
  1. Modify app. vue and helloWorld.vue:
Change <script> to <script lang="ts">Copy the code

Tsconfig. Json includes:

  • compileOnSave
  • Configure compilerOptions
  • Exclude
  • Extends
  • Files (specifies that the file to be compiled, i.e. the entry file, is an array type)
  • Include (compile included files)
  • References (Dependent projects) Package the front and back ends separately
  • TypeAcquisition (set auto-import library type definition file (.d.ts) related)

Tsconfig. ts (root directory) :

{
  //"compileOnSave": true,  /* 设置保存文件的时候自动编译,但需要编译器支持。 */
  "compilerOptions": {
    /* Basic Options */
    "incremental": true,                   /* TS编译器在第一次编译之后会生成一个存储编译信息的文件,第二次编译会在第一次的基础上进行增量编译,可以提高编译的速度Enable incremental compilation */
    "target": "esnext",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    "lib": ["DOM", "ES2015", "ScriptHost", "ES2019.Array"],                             /* 编译过程中需要引入的库文件的列表。 Specify library files to be included in the compilation. */
    "allowJs": true,                       /* Allow javascript files to be compiled. */
    "checkJs": true,                       /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    "declaration": true,                   /* 生成声明文件,开启后会自动生成声明文件 Generates corresponding '.d.ts' file. */
    // "declarationDir": "./file", // 指定生成声明文件存放目录
    // "declarationMap": true,                /* 为声明文件生成sourceMap Generates a sourcemap for each corresponding '.d.ts' file. */
    "sourceMap": true,                     /* 生成相应的 .map文件Generates corresponding '.map' file. */
    "emitDeclarationOnly": true,   /* 只生成声明文件,而不会生成js文件 */
    //"skipLibCheck": true,  /* 忽略所有的声明文件( *.d.ts)的类型检查。 */
    //"outFile": "./",                       /* 将多个相互依赖的文件生成一个文件,可以用在AMD模块中,即开启时应设置"module": "AMD", Concatenate and emit output to single file. */
    "outDir": "./dist",                        /* 指定输出目录 Redirect output structure to the directory. */
    // "rootDir": "./",                       /* 指定输出文件目录(用于输出),用于控制输出目录结构 Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                     /* Enable project compilation */
    // "tsBuildInfoFile": "./",               /* 增量编译文件的存储位置Specify file to store incremental compilation information */
    "removeComments": true,                /* Do not emit comments to output. */
    "preserveConstEnums": true,             /* Preserve the const and enum declarations*/
    // "noEmit": true,                        /* 不输出文件,即编译后不会生成任何js文件 Do not emit outputs. */
    //"noEmitOnError": true,  /* 发送错误时不输出任何文件 */
    //"noEmitHelpers": true, /* 不生成helper函数,减小体积,需要额外安装,常配合importHelpers一起使用 */
    "importHelpers": true,                 /* 通过tslib引入helper函数,文件必须是模块 从 tslib 导入辅助工具函数(比如 __extends, __rest等) */
    "downlevelIteration": true,            /* 降级遍历器实现,如果目标源是es3/5,那么遍历器会有降级的实现 Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    "isolatedModules": true,               /* 将每个文件转换为一个单独的模块Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                           /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                 /* 不允许隐式的any类型 Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* 不允许把null、undefined赋值给其他类型的变量 Enable strict null checks. */
    // "strictFunctionTypes": true,           /* 不允许函数参数双向协变 Enable strict checking of function types. */
    // "strictBindCallApply": true,           /* 严格的bind/call/apply检查 Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true,  /* 类的实例属性必须初始化 Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                /* 不允许this有隐式的any类型 Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* 在代码中注入'use strict' Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* 检查只声明、未使用的局部变量(只提示不报错) Report errors on unused locals. */
    // "noUnusedParameters": true,            /* 检查未使用的函数参数(只提示不报错) Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* 每个分支都会有返回值 Report error when not all code paths in function return a value. */
    "noFallthroughCasesInSwitch": true,    /* 防止switch语句贯穿(即如果没有break语句后面不会执行) Report errors for fallthrough cases in switch statement. */

    /* Module Resolution Options */
    "moduleResolution": "node",            /* 决定如何处理模块:模块解析策略,ts默认用node的解析策略,即相对的方式导入。Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    "baseUrl": "./",                       /* 解析非相对模块名的基准目录,默认是当前目录 */
    "paths": {
      "@/*": [
        "src/*"
      ],
      //"jquery": ["node_modules/jquery/dist/jquery.min.js"]
    },                           /* 模块名到基于 baseUrl的路径映射的列表 A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* 将多个目录放在一个虚拟目录下,用于运行时,即编译后引入文件的位置可能发生变化,这也设置可以虚拟src和out在同一个目录下,不用再去改变路径也不会报错 List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* 声明文件目录,默认时node_modules/@types List of folders to include type definitions from. */
    // "types": [],                           /* 加载的声明文件包 Type declaration files to be included in compilation. */
    "allowSyntheticDefaultImports": true,  /* 允许从没有设置默认导出的模块中默认导入。这并不影响代码的输出,仅为了类型检查。*/
    "esModuleInterop": true,                  /* 允许export=导出,由import from 导入 Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
    // "allowUmdGlobalAccess": true,          /* 允许在模块中全局变量的方式访问umd模块 Allow accessing UMD globals from modules. */

    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* 生成目标文件的inline SourceMap,inline SourceMap会包含在生成的js文件中 Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */

    /* Advanced Options */
    "forceConsistentCasingInFileNames": true,  /* Disallow inconsistently-cased references to the same file. */
    //"listEmittedFiles": true, /* 打印输出文件 */
    //"listFiles": true  /* 打印编译的文件(包括引用的声明文件) */
  },
  "exclude": [
    "node_modules"
  ]
}
Copy the code

Configure shim.d.ts to tell ts that vue is a file type, without which all vUE files imported will be reported as errors.

If you want to introduce other plug-ins, such as vue-echarts, you need to specify the file type here

Shim.d.ts (in the root directory) :

declare module "*.vue" { import { Component } from "vue"; const component: Component; export default component; } Declare Module 'vue-echarts' // Import vue-echartsCopy the code

Or vue-cli can be written like this;

Declare Module '*. Vue '{// Declare declare, Declare an Ambient Module import Vue from 'Vue' export default Vue}Copy the code

3.eslint-prettier

Configure code specifications for projects: this is optional

Configuration eslint:

yarn add -D eslint eslint-plugin-vue babel-eslint
Copy the code

.eslintrc.js:

module.exports = {
  root: true,
  env: {
    node: true,
  },
  extends: [
    'plugin:vue/vue3-essential',
    'eslint:recommended',
    'plugin:prettier/recommended',
  ],
  parserOptions: {
    parser: 'babel-eslint',
  },
  plugins: ['prettier'],
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'no-unused-vars': process.env.NODE_ENV === 'production' ? 'error' : 'warn',
  },
}
Copy the code

Configuration prettier:

 yarn add -D prettier eslint-config-prettier eslint-plugin-prettier
Copy the code

Prettier.config.js (root) :

module.exports = {
    printWidth: 500,
    tabWidth: 2,
    useTabs: false,
    semi: false, 
    vueIndentScriptAndStyle: true,
    singleQuote: true, 
    quoteProps: 'as-needed',
    bracketSpacing: true,
    trailingComma: 'none', 
    jsxBracketSameLine: false,
    jsxSingleQuote: false,
    arrowParens: 'always',
    insertPragma: false,
    requirePragma: false,
    proseWrap: 'preserve',
    htmlWhitespaceSensitivity: 'strict',
    embeddedLanguageFormatting: 'off',
    endOfLine: 'lf',
    editor:{
        wordWrap:'on',
        fontSize:'14',
    }
  }
Copy the code

4.vue-router

Vue router is the official route manager for vue. js. Its deep integration with vue.js core makes building single-page applications a breeze.

Q: What is the difference between vue-router and vue-next-router?

The installation

NPM install vue-router@next -s yarn Add vue-router@nextCopy the code

Create router folder router/index.ts under SRC

index.ts:

import {createRouter, createWebHashHistory, RouteRecordRaw} from 'vue-router'; import HelloWorld from '.. /components/HelloWorld.vue'; const routes: Array<RouteRecordRaw> = [ { path: "/", name: "HelloWorld", component: HelloWorld, }, // { // path: "/about", // name: "About", // // route level code-splitting // // this generates a separate chunk (about.[hash].js) for this route // // which is lazy-loaded when the route is visited. // component: () => // import(/* webpackChunkName: "About" */ "../components/About.vue") // } ]; Export default createRouter({// Specify the route mode, in this case hash mode history: CreateWebHashHistory (), // routes});Copy the code

Introduce router in main.ts:

import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index'
import './index.css'

const app = createApp(App)
app.use(router)
app.mount('#app')
Copy the code

Restart can

yarn dev
Copy the code

5.vuex

Depending on the needs of the project, if the reuse is less and the project data is not complex, it is unnecessary to introduce

Vuex is a state management mode developed specifically for vue.js applications.

Introducing dependencies:

yarn add vuex@next
Copy the code

Create a store folder in the SRC directory: store/index.ts

import { InjectionKey } from 'vue' import { createStore, Store } from 'vuex' export interface State { name: string, count: number } export const key: InjectionKey<Store<State>> = Symbol(); Open mutations = open mutations = open mutations = open mutations = open mutations = open mutations = open mutations = open mutations = open mutations { increment(state) { state.count++ } } })Copy the code

Introduce store in main.ts:

import { createApp } from 'vue'
import App from './App.vue'
import './index.css'
import router from './router/index'
import {store,key} from './store/index'

const app = createApp(App)
app.use(router)
app.use(store,key)
app.mount('#app')
Copy the code

6.Element-Plus

Step 1: Install dependencies:

npm install element-plus --save
Copy the code

Element-plus allows for two options for your project:

Global use:

Here we can configure size and z-index globally: import main.ts

import { createApp } from 'vue'
import App from './App.vue'
import './index.css'
import router from './router/index'
import {store,key} from './store/index'
import ElementPlus from 'element-plus';
import 'element-plus/lib/theme-chalk/index.css';

const app = createApp(App)
app.use(router)
app.use(store,key)
app.use(ElementPlus,{size:'small',zIndex:1000})
app.mount('#app')
Copy the code
On demand:

With the babel-plugin-Component, we introduce only the components we need to reduce the size of the project. Installation:

npm install babel-plugin-component -D
yarn add babel-plugin-import -D
Copy the code

Json. Plugins need to be modified, or if you are using.babelrc you need to change to

{
  "plugins": [
    [
      "component",
      {
        "libraryName": "element-plus",
        "styleLibraryName": "theme-chalk"
      }
    ]
  ]
}
Copy the code

main.ts:

import { createApp } from 'vue'
import { ElButton, ElSelect } from 'element-plus';
import App from './App.vue';
const option = {size:'small',zIndex:1000}
const app = createApp(App)
app.config.globalProperties.$ELEMENT = option
app.component(myBtn, ElButton);
app.component(myElSe, ElSelect);

/* or
 * app.use(ElButton)
 * app.use(ElSelect)
 */

app.mount('#app')
Copy the code

We’re all used to writing styles in less. Vite provides built-in files for.less,.scss, etc. Just install the dependency:

npm install less less-loader --dev
Copy the code

Error: Add package.json:

"Less", "^ 4.4.1", "less - loader" : "^ 8.0.0." "Copy the code

Go to the devDependencies object and re-npm I.

7. Vite configuration file

When you run vite from the command line, vite will automatically parse the file named vite.config.js in the project root directory:

If you don’t want to use viet.config. ts in your project and use my-config.ts instead, you can explicitly specify a configuration file with the –config command line option (resolution will be relative to the CWD path).

npx vite --config my-config.ts
Copy the code

If you do not have @vitejs/plugin-vue, install the @vitejs/plugin-vue dependency

yarn add @vitejs/plugin-vue
Copy the code

vite.config.ts

export default defineConfig({
  alias: {
    '@': pathResolve('./src'),
  },

  server: {
    open: false,
    https: false,
    proxy: {
      '/api': {
        target: 'http://',
        changeOrigin: true,
        ws: false,
        secure: false,
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
    },
    hmr: {
      overlay: true,
    },
  },

  build: {
    terserOptions: {
      compress: {
        drop_console: true,
        drop_debugger: true,
      },
    },

    chunkSizeWarningLimit: 800, 
  },

  plugins: [vue()],
})
Copy the code