Vite is what

Vite is a development and construction tool. In the development process, it uses the browser native ES Module feature to import organizational code, and uses rollup as a packaging tool in production. It has the following features:

  • The speed of light to start
  • Hot Module Replacement
  • According to the need to compile

In this paper, the target

To put it bluntlyviteIs a set of advanced development tools tailor-made for developers. On-demand compilation, hot module replacement and other features allow us to develop without repackaging wait time, the development experience is silky smooth, and the default integrationvue3Is the necessary medicine for family travel and murder. At presentviteIt is already the official version, and the related ecology is booming rapidly. I have also made some explorations in engineering for the first time, hoping to throw off a brick and introduce jade. Welcome to dig friends and clap bricks.

Install vite

$ npm init vite-app <project-name>
$ cd <project-name>
$ npm install
$ npm run dev
Copy the code

Code organization analysis

The key change is the way entry files are imported in index.html

This allows you to organize your code in main.js using ES6 Modules

The browser loads these imports automatically, and Vite starts a local server to handle different load requests. For relative address imports, the file content is processed according to the suffix and returned, and for bare module imports, its path is changed to relative address and processed again.

Then get the file to load according to the entry file option in the module package.json.

There are no big changes overall for developers.

Parsing the resource loading mode

Import the CSS file directly

CSS files can be imported directly from Vite, and styles will affect the imported pages, which will eventually be packaged into style.css.

In our program, most styles exist in the SFC in form except for global styles

Scoped CSS

<style scoped>
/ * * /
</style>
Copy the code

CSS Module

CSS Modules are used in the SFC

<style module>
/ * * /
</style>
Copy the code

Example: Modify component styles to CSS Module style

Import CSS modules from JS: name the CSS file *.module. CSS

CSS preprocessor

Install the corresponding preprocessor and you can use it directly in your Vite project.

<style lang="scss">
/* use scss */
</style>
Copy the code

Or import it in JS

import './style.scss'
Copy the code

PostCSS

Vite automatically applies PostCSS configuration to *.vue files and imported.css files, we just need to install the necessary plug-ins and add postcss.config.js files.

module.exports = {
  plugins: [
    require('autoprefixer'),
  ]
}
Copy the code
NPM I postcss [email protected]Copy the code

Resource URL processing

Referencing static resources

We can refer to static resources in relative and absolute paths in template, style, and pure.css files in *.vue files.

<! -- Relative path -->
<img src="./assets/logo.png">
<! -- Absolute path -->
<img src="/src/assets/logo.png">
Copy the code
<style scoped>
#app {
  background-image: url('./assets/logo.png');
}
</style>
Copy the code
publicdirectory

The public directory can store resources that are not referenced in the source code, they are left behind and their file names are not hashed.

These files are copied verbatim to the root of the distribution directory.

<img src="/logo.png">
Copy the code

Note that references to files placed under public require absolute paths. For example, public/icon. PNG should be referenced using /icon.png

Code specification: ESLint

We use ESLint to standardize project code and format code by prettier.

First install the dependency, package.json, in the project

{
  "scripts": {
    "lint": "eslint \"src/**/*.{js,vue}\""
  },
  "devDependencies": {
    "@vue/eslint-config-prettier": "^ 6.0.0"."babel-eslint": "^ 10.1.0"."eslint": "^ 6.7.2." "."eslint-plugin-prettier": "^ 3.1.3"."eslint-plugin-vue": "^ 7.0.0-0"."prettier": "^ 1.19.1"}}Copy the code

Then configure the Lint rule,.eslintrc.js

module.exports = {
  root: true.env: {
    node: true,},extends: ["plugin:vue/vue3-essential"."eslint:recommended"."@vue/prettier"].parserOptions: {
    parser: "babel-eslint",},rules: {
    "no-console": process.env.NODE_ENV === "production" ? "warn" : "off"."no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off"."prettier/prettier": [
      "warn",
      {
        // singleQuote: none,
        // semi: false,
        trailingComma: "es5",},],},};Copy the code

If necessary, you can modify the default formatting rule for Prettier by configuring prettier.config.js

module.exports = {
  printWidth: 80.// Length per line (default 80)
  tabWidth: 2.// How many Spaces per TAB (default: 2)
  useTabs: false.// Whether to indent with TAB (default false)
  singleQuote: false.// Use single quotes (default false)
  semi: true.// Declaration ends with a semicolon (default true)
  trailingComma: 'es5'.// Use trailing commas for multiple lines (default none)
  bracketSpacing: true.// Use Spaces between braces for object literals (default true)
  jsxBracketSameLine: false.// In multi-line JSX, the > is placed at the end of the last line instead of starting on another line (default false)
  arrowParens: "avoid".// Avoid parentheses for arrow functions with only one argument (default: avoid)
};
Copy the code

The test environment

Test components with Jest and @vue/test-utils

Install dependencies

"jest": "^ 24.0.0"."vue-jest": "^ 5.0.0 - alpha. 3"."babel-jest": "^ 26.1.0"."@babel/preset-env": "^ 7.10.4"."@vue/test-utils": 9 "^ 2.0.0 - beta."
Copy the code

Configure the Babel. Config. Js

module.exports = {
  presets: [["@babel/preset-env", { 
        targets: { 
          node: "current"}}]],};Copy the code

Configuration jest. Config. Js

module.exports = {
  testEnvironment: "jsdom".transform: {
    "^.+\\.vue$": "vue-jest"."^.+\\js$": "babel-jest",},moduleFileExtensions: ["vue"."js"."json"."jsx"."ts"."tsx"."node"].testMatch: ["**/tests/**/*.spec.js"."**/__tests__/**/*.spec.js"].moduleNameMapper: {
    "^main(.*)$": "<rootDir>/src$1",}};Copy the code

The startup script

"test": "jest --runInBand"
Copy the code

Test code, tests/example.spec.js

import HelloWorld from "main/components/HelloWorld.vue";
import { shallowMount } from "@vue/test-utils";

describe("aaa".() = > {
  test("should ".() = > {
    const wrapper = shallowMount(HelloWorld, {
      props: {
        msg: "hello,vue3",}}); expect(wrapper.text()).toMatch("hello,vue3");
  });
});
Copy the code

Lint configuates to add the jEST environment, otherwise you will get an error message:

module.exports = {
  env: {
    jest: true}},Copy the code

Hook Lint, test, and git

npm i lint-staged yorkie -D
Copy the code
"gitHooks": {
  "pre-commit": "lint-staged"."pre-push": "npm run test"
},
"lint-staged": {
  "*.{js,vue}": "eslint"
},
Copy the code

Under normal circumstances submit hook yorkie automatically after installation If not submit hook can manually run the node node_modules/yorkie/bin/the js to install. Of course, you can run the node node_modules/yorkie/bin/uninstall. Js submitted to uninstall hooks.

Typescript integration

Vite can be directly imported into. Ts files and used in SFC by

Example: Create a component using TS

<script lang="ts">
import { defineComponent } from 'vue'

interface Course {
  id: number;
  name: string;
}
  
export default defineComponent({
  setup() {
    const state = ref<Course[]>([]);
    setTimeout(() = > {
      state.value.push({ id: 1.name: "Full stack Architect" });
    }, 1000); }}); </script>Copy the code

Ts version specified, package.json

{
  "devDependencies": {
    "typescript": "^ 3.9.7." "}}Copy the code

Ts reference configuration, tsconfig.json

{
  "compilerOptions": {
    "target": "esnext"."module": "esnext"."moduleResolution": "node"."isolatedModules": true."strict": true."noUnusedLocals": true."noUnusedParameters": true."experimentalDecorators": true."lib": ["dom"."esnext"]},"exclude": ["node_modules"."dist"]}Copy the code

Project configuration

The project root directory creates vite. Config. js, and you can deeply configure the Vite project.

Define an alias

Import aliases that avoid large numbers of relative paths, elegant and error-proof

Define an alias for SRC/Components, vite. Config.js

const path = require("path");

module.exports = {
  alias: {
    // Pathmaps must start and end with a slash
    "/comps/": path.resolve(__dirname, "src/components"),}};Copy the code

use

import CourseAdd from "/comps/CourseAdd.vue";
import Comp from "/comps/Comp.vue";
Copy the code

The agent

Configure the server proxy, vite.config.js

export default {
  proxy: {
    '/api': {
      target: 'http://jsonplaceholder.typicode.com'.changeOrigin: true.rewrite: path= > path.replace(/^\/api/.' ')}}}Copy the code

use

fetch("/api/users")
  .then(response= > response.json())
  .then(json= > console.log(json));
Copy the code

The mock data

Install dependencies

npm i mockjs -S
npm i vite-plugin-mock cross-env -D
Copy the code

Introduce the plugin, vite.config.js

plugins: [
  createMockServer({
    // close support .ts file
    supportTs: false,})],Copy the code

Set the environment variable, package.json

"dev": "cross-env NODE_ENV=development vite"
Copy the code

Create the mock file, mock/test.js

export default[{url: "/api/users".method: "get".response: req= > {
      return {
        code: 0.data: [{name: "tom"}, {name: "jerry",}]}; }, {},url: "/api/post".method: "post".timeout: 2000.response: {
      code: 0.data: {
        name: "vben",},},},];Copy the code

Patterns and environment variables

Use mode to configure multiple environments. The default mode is Development for Vite serve and Production for Vite build.

Create a configuration file. Env.development

VITE_TOKEN=this is token
Copy the code

Read from code

import.meta.env.VITE_TOKEN
Copy the code

Packaging and deployment

packaging

Use NPM run build to perform packaging

The deployment of

Manually uploading the dist to the server and configuring nginx is certainly possible, but this process should be automated to avoid the previous tedious operations. Here we use Github Actions to implement the CI/CD process.

Github Actions allows you to create custom software development life cycle workflows directly from the Github repository.

Preparations:

Aliyun Linux server

Linux operating

Ali Cloud related operations

Step 1: configure the workflow, the following configurations can be automatically when we push the code package and deploy our application to ali cloud server, in the project root directory to create. Making/workflows/publish. Yml

name: Package the app and upload it to Aliyun

on:
  push:
    branches:
      - master

jobs:
  build:
    # runs-on Specifies the VIRTUAL machine environment required by the job to run the job (required field)
    runs-on: ubuntu-latest
    steps:
      # get source code
      - name: Out of the code
        # use actions/checkout to fetch the source code
        uses: actions/checkout@master
      # installation Node10
      
      - name: Installation node. Js
        Install node using actions/setup-node
        uses: actions/setup-node@v1
        with:
          node-version: 14.0. 0

      # install dependencies
      - name: Install dependencies
        run: npm install

      # packaged
      - name: packaging
        run: npm run build

      # upload Aliyun
      - name: Publish to Aliyun
        uses: Easingthemes/[email protected]
        env:
          # the private key
          SSH_PRIVATE_KEY: The ${{ secrets.PRIVATE_KEY }}
          # SCP parameters
          ARGS: "-avzr --delete"
          # source directory
          SOURCE: "dist"
          # server IP: Use your server IP
          REMOTE_HOST: "47.98.252.43"
          # the user
          REMOTE_USER: "root"
          # destination address
          TARGET: "/root/vue-in-action"
Copy the code

Step 2: Set the private key option under the current Github project

Copy the local private key, ~/.ssh/id_rsa

The SSH key generation process is self-generated
cd .ssh/
cat id_rsa
Copy the code

Copy and fill into github-secretes

Step 3: Configure Nginx on Ali cloud server

Logging In to the Server

SSH [email protected]# change the IP to yours
Copy the code

Configure nginx

cd /etc/nginx/sites-enabled/
vi vue-in-action
Copy the code

Add the following configuration

server {
    listen 8080;
    server_name 47.98.252.43;
    location / {
        root /root/vue-in-action/dist/;
        indexindex.html index.htm; }}Copy the code

Nginx: nginx -s reload

Step 4: Push code triggers workflow

We’re done. Excited. Let’s verify the upload results

Visit: 47.98.252.43:8080 try the effect!!

Supporting video demonstration

I have specially recorded a set of videos to demonstrate all the operations done in this article.

“Village chief” Vite engineering

Production is not easy, for a 3 concern is not too much! ?

The follow-up plan

In the follow-up, I plan to integrate a series of project practices, including but not limited to the following contents:

  • Style of management
  • The page layout
  • Access control
  • Icon management
  • Request to packaging
  • Data visualization

Let’s give it a thumbs up and bookmark it for future study.

Support the village chief

About engineering said here, this content toss about for a long time, stepped on a lot of pits, dropped a few hair, small partners point a praise 👍 to encourage.

My recent post (thanks for the encouragement and support of Digifriends 🌹🌹🌹) :

  • 🔥 to prepare for 2021, VUE3 version of probe flying card effect components to achieve 35👍
  • 🔥 Another night, does this Composition-API feel short 211👍
  • 🔥 win vue3 you have to prepare 65👍
  • 🔥 Lightning Five Whip: An in-depth analysis of Composition API 52👍