preface

Today, I rebuilt the project framework using Vite2 from the original personal project I created using VUe-CLI, stomped a few holes along the way, but ended up running fine in both local and production environments. With that in mind, I’m sharing my potholes to help readers avoid any detours.

Create a project using Vite

It is not the purpose of this article to introduce vite, but the basic process of creating a project will need to be copied from the official copy to show the reader:

Use NPM:

$ npm init vite@latest
Copy the code

Using Yarn:

$ yarn create vite
Copy the code

Use the PNPM:

$ pnpx create-vite
Copy the code

Then follow the prompts to operate!

Install dependencies in vuE-CLI project

I created the Vite project, used vuE-TS as the template, and installed the dependencies. At this point, I copied all the code parts from the VUE-CLI project into the Vite project, considering that the vue-CLI project dependencies need to be completed.

The dependencies I need for the production environment include: Axios, Element-Plus, LoDash, VUE-Router, Vuex, Vuex-PersistedState.

Here, if I simply install these dependencies once, I hit the first pitfall.

1. Production environment dependency

My idea is to install the latest version of these dependencies directly, so type in the console:

yarn add axios element-plus lodash vue-router vuex vuex-persistedstate
Copy the code

As a result, vue-Router and Vuex are not installed with version 4.0 as expected, but with the latest versions of 3.x, since the current mainstream versions are their vue2 counterparts [email protected] and [email protected]. I want to install vue-Router and Vuex 4.0. Enter the following command on the console:

Yarn add vue - the router @ ^ 4.0.0 vuex @ ^ 0 4.0.0-0Copy the code

Problem solving 😏

2. Development environment dependency

If you have your own project created using vue-CLI, open the package.json file and you can see that there are many dependencies on the development environment in your project.

The answer is no. At least the part that vuE-CLI comes with is not needed. The part that you add is subject to the specific situation.

The only development dependencies in my project are those installed by default when vue-CLI is created, including Node-sass and Sass-Loader. Since I use Sass in my project, I need to install these two dependencies when creating the project using VUe-CLI.

If you know anything about Vite and are relatively careful, you know that these two dependencies don’t necessarily need to be installed in a Vite project. But I didn’t think much about it until I packed it into production.

Since Node-sass and Sass-Loader are dependencies that work with WebPack, and WebPack is not available in Vite (it has rollup, but I’m not familiar with it), there should be no need to install them. There is no need to install the above two dependencies, but sASS support is needed for sASS files to be converted to CSS in the project, so here I need to install Sass:

yarn add --dev sass
Copy the code

3. Modify vite. Confg

In a vue-cli project, the global configuration file is vue.config.js, and in a Vite project, it is vuite.config.ts in the root directory.

In the VUe-CLI project, I have configured the project alias, devServer, and the packaged directory name. I also need to configure these points in the Vite project. I’ll post the code directly and explain it later:

import { defineConfig } from "vite"; import vue from "@vitejs/plugin-vue"; import path from "path"; function resolve(dir: string) { return `${path.resolve(__dirname, dir)}/`; } export default defineConfig({ resolve: { alias: { "@/": resolve("src/"), }, }, plugins: [vue()], server: { port: 8080, proxy: {"/ API ": {// proxy: {"/ API ": {// proxy: {"/ API ": {// target: "http://127.0.0.1:4000", changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, ""), }, }, }, build: { outDir: "music-player", }, });Copy the code

In terms of setting up the package code output directory is controlled by setting build.outdir, I’ll focus on alias Settings and server configuration.

1. Alias Settings

In the VUe-CLI project, I used the @ alias a lot, and I needed to do the same in the Vite project, so it was inevitable to set the alias. In addition to the key: value mode in the code above, the alias also supports the array {find, replacement}. It is written as follows:

alias: [{
    find: "@/",
    replacement: resolve("src/"),
 }],
Copy the code

The reader can find out for himself why the alias is spliced with a /. Another point is that typescript errors still occur when @ paths are used in the code after aliasing is configured, so you need to modify the tsconfig.json file to add paths to the compilerOptions configuration:

   "baseUrl": ".",
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
Copy the code

2. The server Settings

Let’s start with the configuration of the development environment server in the Vite project and vuE-CLI project:

Vite projects:

Server: {port: 8080, proxy: {"/ API ": {// All interfaces starting with/API are proxy to the domain name specified by target. Target: "http://127.0.0.1:4000", changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, ""), }, }, },Copy the code

Vue – cli project:

DevServer: {proxy: {"/" : {target: "http://127.0.0.1:4000",},},},Copy the code

In vite, virtually all requests to/API are directed to http://127.0.0.1:4000; This is not required in vue-CLI. In my opinion, vite actually forwards/API requests to http://127.0.0.1:4000. Because Vite actually treats the page and interface as a resource, if I change the/API to/then all requests for port 8080 go to port 4000. Readers need to take note of this.

Vue -router configuration file is stomped

The way dynamic imports are written in Vue-Router has also changed in Vite.

First post some of my code:

@param {string} view path relative to the SRC directory */ export function lazyLoad(viewPath: string) { const modules = import.meta.glob(".. /views/**/*.vue"); return modules[`../views/${viewPath}.vue`]; } const routes: Array<RouteRecordRaw> = [ { path: "/", name: "Home", component: lazyLoad("home/Home"), children: [ { path: "/", name: "Personal", component: lazyLoad( "home/components/main-content/views/personal-recommends/index" ), }, ], }, ];Copy the code

Vite supports importing multiple modules from the file system using the special import.meta.glob function:

const modules = import.meta.glob('./dir/*.js')
Copy the code

The above will be translated as follows:

/ / vite generated code const modules = {'. / dir/foo. Js' : () = > import ('. / dir/foo. Js'), '. / dir/bar. Js' : () => import('./dir/bar.js') }Copy the code

Please refer to the official documentation for details

Readers can refer to my writing method and adapt to the actual situation.

4, main.ts file stomp pit

  1. Import import “element – plus/dist/index. The CSS”; Replace the import “element – plus – chalk/index/lib/theme. CSS”;

  2. Automatic global registration of basic components, due to the absence of Webpack, the lack of Webpack require.contextAPI, this part of the function can only be discarded. I do not know whether there is a good solution for readers.

I encountered a pit impressed is probably these a few, welcome readers in the comments discussion.

Finally, a small AD for my own open source project:

Vue3.2 + typescript copy netease Cloud Music for Mac github: github.com/callmehui/w… Online access address (packaged with Vite) : music-player.immortalboy.cn/

Welcome to star, welcome to fork, welcome to Issue 👏.