Detailed introduction and practice of vue+ts+vite

Vite is a tool for front-end code packaging. First, you can understand the packaging and construction method of Vite through a picture.
Insert image description here

1. Prerequisite knowledge: npm and yarn package managers

1. npm common commands and instructions

// 查看npm版本
npm -v

// 初始化一个项目,会出现一个package.json配置文件,可以在后面加上-y ,快速跳过问答式界面
npm init

// 安装依赖包
npm install // 根据项目中的package.json文件自动下载项目所需的全部依赖
npm install 包名 --save-dev (npm install 包名 -D) // 安装的包只用于开发环境,不用于生产环境,会出现在package.json文件中的devDependencies属性中。
npm install 包名 --save (npm install 包名 -S) // 安装的包需要发布到生产环境的,会出现在package.json文件中的dependencies属性中

// 更新
npm update 包名 // 更新指定包

// 移除依赖包
npm uninstall 包名 // 卸载指定包

// 查看
npm list // 查看当前目录下已安装的node包
npm list -g // 查看全局已经安装过的node包
npm info 指定包名 // 查看远程npm上指定包的所有版本信息
npm config list // 查看配置信息
npm ls 包名 // 查看本地安装的指定包及版本信息,没有显示empty
npm ls 包名 -g // 查看全局安装的指定包及版本信息,没有显示empty
npm root // 查看当前包的安装路径
npm root -g // 查看全局的包的安装路径

// 其他
npm config set registry https://registry.npm.taobao.org //  修改包下载源,此处修改为了淘宝镜像
npm --help // 查看npm帮助命令
npm 指定命令 --help // 查看指定命令的帮助

2. Yarn common commands and instructions

// 初始化一个新项目
yarn init 

// 运行脚本
yarn run // 用来执行在 package.json 中 scripts 属性下定义的脚本

// 发布包
yarn publish

// 添加依赖包
yarn add [package] // 会自动安装最新版本,会覆盖指定版本号
yarn add [package] [package] [package] // 一次性添加多个包
yarn add [package]@[version] // 添加指定版本的包
yarn add [package]@[tag] // 安装某个tag(比如beta,next或者latest)

// 将依赖项添加到不同依赖项类别,不添加则默认安装到package.json中的dependencies里
yarn add [package] --dev 或 yarn add [package] -D // 加到 devDependencies
yarn add [package] --peer 或 yarn add [package] -P // 加到 peerDependencies
yarn add [package] --optional 或 yarn add [package] -O // 加到 optionalDependencies

// 升级依赖包
yarn upgrade [package] // 升级到最新版本
yarn upgrade [package]@[version] // 升级到指定版本
yarn upgrade [package]@[tag] // 升级到指定tag

// 移除依赖包
yarn remove [package] // 移除包

// 安装package.json里的包依赖,并将包及它的所有依赖项保存进yarn.lock
yarn 或 yarn install // 安装所有依赖
yarn install --flat // 安装一个包的单一版本
yarn install --force // 强制重新下载所有包
yarn install --production // 只安装生产环境依赖

// 显示某个包的信息
yarn info [package] // 可以用来查看某个模块的最新版本信息

// 缓存相关
yarn cache
yarn cache list // 列出已缓存的每个包
yarn cache dir // 返回全局缓存位置
yarn cache clean // 清除缓存

2. Create a vite project

Make sure the node version needs to be above 12.0
Insert image description here

1. Install the latest version of vite official website

npm init vite@latest // 安装最新版本的vite

This article shows how vue+tsto build a project based on the latest version of vite, and follow the instructions to run the project.
Insert image description here

cd "项目名称" // 进入项目目录
npm instasll // 安装依赖包
npm run dev // 运行项目

Insert image description here

Insert image description here

2. Install vite1.x version

Install the vite project command: yarn create vite-app "项目名称"or npm init vite-app + "项目名称"
as follows: (not recommended)
Insert image description here
Insert image description here
Insert image description here
At this point, a vite project has been successfully created and run.

3. Directory structure analysis

The initial structure of the vite+vue+ts project directory is as follows:
Insert image description here

1、.vscode

The files in this directory extensions.jsonrecord the configuration related to the development tool vscode.

2、node_modules

By executing the installation command npm installor yarnautomatically generated dependency package directory.

3、public

Vite will copy all files placed in the public folder intact to the root directory of the packaged folder.
Things to note when using files in public: 1) You should always use the root directory /to reference files in the public folder, such as using /favicon.icoto reference public/favicon.icofiles; 2) Files in public cannot use javascript to import resources.

4、src

Project-related resource code storage location.

1)assets

Used to store all static resource files (css, fonts, etc.) in the project.

2)components

Used to store all custom components in the project.

3)App.vue

Is the root component of the project.
Insert image description here

4)main.ts

It is the entrance to the entire project.
Insert image description here

5)style.css

A basic style file table that is global to the entire project.

6)vite-env.d.ts

Insert image description here
In projects developed using ts, .d.tsthe file at the end is mainly used for TypeScript to identify .vuefiles. .vueThe file is not a regular file type. ts cannot understand vuewhat the file is for. Here, ts is told that the vue file is of this type. Without the declaration file in this file declare, you will find importthat all vue type files will report errors. And js itself has no type. The language service of ts needs the .d.ts file to identify the type, so that the corresponding syntax check and intelligent prompt can be achieved.

5、.gitignore

Files ignored when submitting code to the git repository. It identifies which files do not need to be submitted to the git repository. The contents can be specific folders or file suffixes, as shown below.
Insert image description here

6、index.html

The only html page entry file in the SPA single-page application, Vite index.htmlthinks of it as and the URL base will be automatically reset.
Insert image description here
For projects packaged with vue+ts+webpack, it main.tsis regarded as the entry point, index.htmlbut is placed in publica folder and used as a template. When building resources, resource links will be automatically injected into index.htmlthe file and can be used <%=BASE_URL%>to insert content.

7、package-lock.json

Contains information about the exact version of each dependency installed, as well as a checksum of the code to ensure the code is exactly the same. This file locks the version of each dependency you installed. This ensures you don't install bad dependencies. , and will avoid bad situations caused by developers accidentally changing or updating the version. Generally, this file will not be modified easily. The simple understanding is: lock the version of the dependency package to ensure that others can get the same dependency environment when they use npm to install the dependency package of the project. If the command executed when installing the package in subsequent development is: npm install [email protected], then package-lock.jsonthis file will be modified simultaneously.
ps : If the command executed before installing the dependent package is not, npmthen yarnthis file does not exist, but a yarn.lockfile is generated, whose function is also to lock the version number of the package during installation.

8、package.json

Project description file, which records information related to the current project. The details are as follows:

{
    
    
  "name": "vite-project", // 项目名称
  /*
  主要是防止执行了npm publish发布了不想发布的包,或发布到不想发布的npm私服,
  只有移除掉该属性才能执行发布命令npm publish,
  如果不想每次新建项目都手动设置,可以进行全局配置:npm config set init-private true
  */
  "private": true,
  "version": "0.0.0", // 项目版本
  /*
  用于定义package.json文件和该文件所在目录根目录中.js文件和无拓展名文件的处理方式。
   值为'moduel'则当作es模块处理,值为'commonjs'则被当作commonJs模块处理,不指定值则默认按照commonJs规范处理。
   但无论type字段为何值,.mjs的文件都按照es模块来处理,.cjs的文件都按照commonJs模块来处理
  */
  "type": "module", 
  "scripts": {
    
      // scripts中配置以键值对(key:value)的形式来取“别名”
    "dev": "vite", // 项目运行命令,文中第一步运行npm run dev就是从这得到的,如果名称dev换成了serve,那么在运行项目时的命令就是:npm run serve
    "build": "vue-tsc --noEmit && vite build", // 项目打包命令,打包项目时执行:npm run build
    "preview": "vite preview"
  },
  // 正式环境依赖所需要的第三方模块(包),安装命令一般是:npm install "依赖包名"
  "dependencies": {
    
    
    "vue": "^3.2.37"
     /* 包名: 版本号
    	版本号前面的符号一般有两种:~ ,^,区别:
    	^的意思是最近的一个大版本,比如 ^1.0.2 将会匹配所有 1.x.x, 但不包括2.x.x
    	~的意思是匹配最近的小版本,比如 ~1.0.2 将会匹配所有的1.0.x版本,但不匹配1.1.0
    	如果没有上面这2种符号,则表示安装精确的版本
	*/
  },
   /*
  	开发时依赖所需要的第三方模块(包),安装命令一般是:npm install -D "依赖包名",或 npm install --save-dev "依赖包名" ,
  	如:新增sass包可执行命令npm install -D sass 或 npm install --save-dev sass 
  特别注意要加-dev表示是开发时用的依赖包
  */
  "devDependencies": {
    
    
    "@vitejs/plugin-vue": "^3.0.0", // @vitejs/plugin-vue 插件会将 .vue 文件编译并拆分成三个部分,包括模版,脚本和样式
    "typescript": "^4.6.4",
    "vite": "^3.0.0",
    "vue-tsc": "^0.38.4"
  }
}

9、README.md

Generally used to record project-related instructions.

10、tsconfig.json

Configuration file of the TypeScript compiler. The TypeScript compiler can compile the code according to its rules.

{
    
    
  "compilerOptions": {
    
    
    "target": "ESNext", // 目标语言的版本
    "useDefineForClassFields": true, // 标志用作迁移到即将推出的类字段标准版本的一部分,默认:false。
    "module": "ESNext", // 生成代码的模板标准
    "moduleResolution": "Node", // // 模块解析策略,ts默认用node的解析策略,即相对的方式导入
    "strict": true, // 是否启动所有严格检查的总开关,默认:false,启动后将开启所有的严格检查选项。
    "jsx": "preserve", // 指定 jsx 格式
    "sourceMap": true, // 生成目标文件的sourceMap文件
    "resolveJsonModule": true, // 是否解析 JSON 模块,默认:false。
    "isolatedModules": true, // 是否将每个文件转换为单独的模块,默认:false。
    "esModuleInterop": true, // 是否通过为所有导入模块创建命名空间对象,允许CommonJS和ES模块之间的互操作性,开启改选项时,也自动开启allowSyntheticDefaultImports选项,默认:false。
    "lib": ["ESNext", "DOM"], // 指定项目运行时使用的库。
    "skipLibCheck": true  // 是否跳过声明文件的类型检查,这可以在编译期间以牺牲类型系统准确性为代价来节省时间,默认:false。
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"], // 解析的文件
  "references": [{
    
     "path": "./tsconfig.node.json" }] // 项目引用,是TS3.0 中的一项新功能,它允许将 TS程序组织成更小的部分。
}

For more configuration and instructions, please refer to: tsconfig.json detailed configuration and ts documentation

11、tsconfig.node.json

Plug-in type configuration file in vite, fields tsconfig.jsonin the file referencesare used.

12、vite.config.ts

Vite build-related configurations, the default content is as follows:
Insert image description here
In actual development, common configurations and instructions can be referred to as follows:

import {
    
     defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path' // 需要安装的插件@types/node
import viteCompression from "vite-plugin-compression"; // gzip必备插件,需要安装:npm i vite-plugin-compression -D
export default defineConfig({
    
    
  base: "./", //  生产环境路径,类似publicPath,'./'避免打包访问后空白页面,要加上,不然线上也访问不了
  // 代理相关配置
  server: {
    
    
    host: "localhost", // 服务器主机名
    port: 3001, // 端口号
    strictPort: false, // 若3000端口被占用,是否直接结束项目
    https: false, // 是否开启 https
    open: true, // 是否自动在浏览器打开
    proxy: {
    
    
      "/api": {
    
    
        target: "", // 后台接口
        changeOrigin: true,
        secure: false, // 如果是https接口,需要配置这个参数
        // ws: true, // websocket是否支持
        rewrite: (path) => path.replace(/^\/api/, ""),
      },
    },
  },
  // 打包相关
  build: {
    
    
    target: "es2020", //指定es版本,浏览器的兼容性
    outDir: "dist",
    assetsDir: "assets", // 指定静态资源存放路径
    // cssCodeSplit: true, // css代码拆分,禁用则所有样式保存在一个css里面
    sourcemap: false, // 是否构建source map 文件
    // manifest: true, // 是否在outDir中生成 manifest.json
    rollupOptions: {
    
    
      // input: '/path/to/main.ts' // 覆盖默认的 .html 入口
    }
  },
  resolve: {
    
    
    // 配置项目路径别名,在开发时不需要写完整的路径名称,需要安装 @types/node,执行命令npm i -D @types/node --save-dev即可
    alias: {
    
    
      "@": path.resolve(__dirname, "src"),
      "@assets": path.resolve(__dirname, "src/assets"),
      "@components": path.resolve(__dirname, "src/components"),
    },
  },
  // 引入第三方的配置
  optimizeDeps: {
    
    
    include: [],
  },
  // 插件相关配置
  plugins: [
    vue(),
    viteCompression({
    
    
      verbose: true,
      disable: false,
      threshold: 10240,
      algorithm: "gzip",
      ext: ".gz",
    })
  ]
})

Because the project uses ts, after configuring the path alias, you need to add the following configuration to the tsconfig.json configuration file:
Insert image description here

For more detailed configuration, please check the vite official website .

13、其他

1).gitignore

In fact, development generally involves submitting code to the git repository. .gitignoreThe files recorded are the files that are ignored when submitting the code to the git repository. It identifies which files do not need to be submitted to the git repository. The contents can be specific folders or file suffixes, as shown below.
Insert image description here

2)dist

npm run buildThe directory generated after executing the packaging command .
Insert image description here
At this point, the basic directory analysis of the Vite project has been completed. In the subsequent development process, you can add directories and other operations by yourself.

4. Static resource processing

1. Introduce resources as url

import imgUrl from './img.png' // 通过import导入图片时,会自动生成一个url,可直接使用

This method is similar to webpack file-loader, the difference is that vite importcan use public absolute paths.

2. To import resources as strings
import testString from './testString?raw, you only need to add the ?raw suffix when importing files.

3. Introduce resources as workers

import Worker from './testWorker.js?worker // 只需要在文件后面加上 ?work
const worker = new Worker()

// 将worker作为base64字符串引入,则需要加上inline
import WorkerBase64 from './testWorkerBase64.js?worker&inline 

5. Environment variables and modes

Mode refers to the environment in which the current project runs. When using npmor yarnexecuting commands, each command can correspond to a mode. The default npm run devexecution environment is developmentthe mode, and npm run buidthe execution environment is productionthe mode. Other settings and execution commands can be customized.

A will be exposed inside Vite import.meta.env, and you can use import.meta.env.xxxto get the configured environment variables.

Built-in variable available in all situations:
import.meta.env.MODE: {string}The mode in which the application is running.
import.meta.env.BASE_URL: {string}The basics when deploying applications are determined URLby baseconfiguration items.
import.meta.env.PROD: {boolean}Whether the application is running in a production environment.
import.meta.env.DEV: {boolean}Whether the application is running in a development environment (always the import.meta.env.PRODopposite).

If you need Vite to configure environment variables similar to Vue2, rely on .envfolders to achieve this. Create .env.productionand under the same level of src .env.developmentto represent the production environment and development environment respectively.
Insert image description here
In addition developmentto productionthese two modes, you can also customize other modes and --modeoverwrite the original modes by passing options. For example, to define a staging mode, you need to create the corresponding .env.stagingfile and execute it. vite build --mode staging
Insert image description here
Another way to modify the execution environment can be package.jsonin Set, and then execute the corresponding command. After that, import.meta.envthe environment variable value obtained by the project is --modethe corresponding value. Execute as follows:npm run serve
Insert image description here

at last

Reference: vite official website

If there is any incorrect understanding in the article, please feel free to give me some advice, let’s learn and grow together~

Guess you like

Origin blog.csdn.net/ganyingxie123456/article/details/126265566