📚 This series covers technical and general knowledge
- 1, vite2. X
- 2, vue3.2. X
- 3, typescript
- 4, Vuex (state management pinia can also be used) create method: new vuex.store (…) (vuex3), createStore (…). (vuex4).
- Vue router 4.x
- 6. Axios encapsulation
- 7, mobile terminal style adaptation
- 8. Use the Vant component library
- 9. Configure environment variables
- 10, SCSS
- 11, rem
Ps: There will also be some questions or problems encountered when creating the framework summary and answers
☞ Technical knowledge point understanding: vite
❓ vite is what
Official website: vitejs.cn/guide/.
vite
French for “fast,” pronounced/vit/
, pronounced “veet”), is a development build tool that significantly enhances the front-end development experience. It uses a browser during developmentnative ES Module
Feature import organization code for production utilizationrollup
As a packaging tool. It has the following characteristics:
- Light speed start, cold service start
- Hot module replacement, hot update during development
- Compile on demand without flushing the entire DOM
Q&a time:
🙋 Q: 1. Some may ask that Vite is a development build tool, but what about the production environment?
A: It packages your code using Rollup, and it is pre-configured to output highly optimized static resources for production.
🙋 Q: 2. What does it mean to import organizational code using the browser native ES Module feature during development?
A: For modern browsers, it is based on the native Module system, which is faster than webPack development environment, because webPack development needs to be compiled and stored in memory.
Conclusion:
In fact, Vite is a set of advanced development tools tailored 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 integration of VUE3. Now that Vite is officially available, the ecosystem is booming.
🧩 Vite2 build tool pros and cons
Contrast the traditional tool development environment with Vite
Traditional tool building:
Vite build method:
1. We can see that:
- Traditional tool build: When cold starting the development server, the packager-based startup must first grab and build your entire application before it can be served.
- Vite: Improved development server startup time by separating application modules into dependent and source modules at the beginning.
Vite improvement
- Vite improves development server startup times by initially separating application modules into dependent and source modules.
- The dependencies are mostly pure JavaScript and do not change at development time. Some large dependencies, such as component libraries with hundreds of modules, are also expensive to handle. Dependencies are also often split into a large number of smaller modules in some way (such as ESM or CommonJS).
- Vite will pre-build dependencies using esBuild. Esbuild is written using Go and is 10-100 times faster than a prepacker-built dependency written in JavaScript.
- The source code usually contains files that are not directly JavaScript that need to be transformed (such as JSX, CSS, or Vue/Svelte components) and often edited. Also, not all source code needs to be loaded at the same time. (for example, code modules based on route splitting).
- Vite serves source code in a native ESM way. This essentially lets the browser take over part of the packaging: Vite simply transforms the source code when the browser requests it and makes it available on demand. Code that is dynamically imported according to the situation is only processed if it is actually used on the current screen.
2. Build differently
- Traditional tool construction: Node.js is used to implement it
- Vite will be used
esbuild
Prebuild dependencies.
Vite improvement
- Vite will be used
esbuild
Prebuild dependencies. Esbuild is written using Go and is better thanNode.js
Written packers prebuild dependencies 10-100 times faster.
3. Thermal update efficiency
- Traditional tool build: When started based on a packer, the file itself is rebuilt after editing it. Obviously, we should not rebuild the entire package, as the update speed would plummet as the application grew in size.
Some of the packer’s development servers store the build content in memory, so they only need to inactivate a portion of the module diagram when the file changes, but it still needs to rebuild the entire page and reload the page. This is expensive, and reloading the page eliminates the current state of the application, so the packer supports dynamic module hot reload (HMR) : allowing a module to “hot replace” itself without affecting the rest of the page. This greatly improves the development experience – however, in practice we have found that even HMR update rates decrease significantly as the application size increases.
-
Vite improvement
- In Vite, HMR is executed on native ESM. When you edit a file,
Vite only needs to precisely invalidate the chain between the edited module and its nearest HMR boundary (most of the time just the module itself), making HMR updates always fast, regardless of the size of the application
. - Vite also uses HTTP headers to speed up whole page reloads (again letting the browser do more for us) : requests from source modules are negotiated in the Cache according to 304 Not Modified, while dependent module requests go through cache-control: Max-age =31536000,immutable Strong cache, so once cached they do not need to be requested again.
- In Vite, HMR is executed on native ESM. When you edit a file,
The advantages and disadvantages
Vite advantages | Vite shortcomings |
---|---|
Development servers are 10-100 times faster than Webpack | Only for modern browsers (ES2015+) |
Make code-splitting a priority | Not fully compatible with CommonJS modules |
Minimum scaffolding excludes Vuex, router, etc | |
Different development servers and build tools | |
Not as ecological as Webpack | |
Prod environment builds, currently using Rollup (esBuild is not very CSS and code splitting friendly) | |
It hasn’t been used on a large scale, and a lot of problems or appeals haven’t really been exposed |
⚙ use
1. Understanding compatibility
Vite requires node.js version >= 12.0.0.Copy the code
Node-v displays the node.js version
Ps: it is recommended to use VScode and install volar, install volar must be closed vetur, otherwise there will be conflicts
2. Vite creates projects
NPM init Installs Vite when initializing the project
#npm 6.x
npm init @vitejs/app <project-name> --template
Copy the code
# NPM 7+ requires additional double lines:
npm init @vitejs/app <project-name> -- --template
Copy the code
#yarn
yarn create @vitejs/app <project-name> --template
Copy the code
#pnpm
pnpm create vite <project-name> -- --template vue
Copy the code
NPM -v You can view the NPM version number
When we select a framework, we can see that we can select different frameworks, If you use Select A Variant without Select A Framework, use VUE – TS. If you don’t want to use TS, use Vue
If you do not want to select, you can use any quick command
npm init @vitejs/app <project-name> --template vue-ts
Copy the code
Continue to:
cd <project-name>
npm install
npm run dev
Copy the code
Second: we can use create-viet-app to install vite independently first
npm install create-vite-app -g
create-vite-app <project-name>
cd <project-name>
npm install
npm run dev
Copy the code
Third: Use open source templatesfast-vue3
Recently, uVU launched an open source template fast-vue3 on Github to provide scaffolding out of the box to quickly get through a start (various configurations) and directly experience the acceleration phase (actual projects). Fast-vue3, is vue3 +Vite2.7+TypeScript+Pinia and other Vue development tool chain. Sorted out the current more mainstream tool chain, can be used directly out of the box, convenient for small partners to learn, the best way to learn – while learning while learning
Features:
fast-vue3
Without further elaboration, frame base supportVue3 + Vite2.7 + + Pinia TypeScript
- Husky and Lint-staged support is a must for large factory team code specification collaboration
- ️ support
svg
The icon has been encapsulated with a simpleSvgIcon
Component that can be read directly under the filesvg
- support
Plop
, code files are automatically generated, and three preset templates are providedpages
.components
.store
And so can be customized - support
Axios (ts)
, has encapsulated the mainstream interceptor, request invocation, and other methods - support
router,store
Modular, built-in generated routing hooks - support
env
, environment variables and differentiate packaging environment - support
unplugin-vue-components
Automatic component import - support
vw/vh
Mobile layout is compatible and can also be usedplop
Configure the build file yourself - support
vite-plugin-md
Markdown rendering - support
vite-plugin-pages
A plug-in that automatically generates routes from files
git clone https://github.com/MaleWeb/fast-vue3.git
cd fast-vue3
pnpm install
pnpm run dev
Copy the code
You can also develop your project using the Template branch, which does not contain any sample code
git clone -b template https://github.com/MaleWeb/fast-vue3.git
Copy the code
⛑ note:
When we install the project, if we use NPM, we always use NPM; If you use PNPM, always use PNPM. Or other installation, but to maintain the overall consistency, otherwise there will be package version error; (Also includes other dependencies for subsequent installations)
Q&a time:
🙋 Q: Why not Internet access? Only http://localhost:3000/
A: You can see that NPM run dev has a line after it: Network: use–host ‘to expose
First: add –host 0.0.0.0 to package.json
"Scripts ": {"dev": "vite --host 0.0.0.0", "build": "vue-tsc --noEmit && vite build", "preview": "vite preview"}Copy the code
The second method: add –host 0.0.0.0 to vite.config.ts
Export default defineConfig({plugins: [vue()], server: {host: "0.0.0.0" //Copy the code
3, Vite create code simple analysis
3.1. It can be seenindex.html
In the import file import modetype="module"
3.2 in the framework codemain.ts
You can use ES6 Module to organize your code
Let’s take a look at what main.ts looks like when it’s loaded in the browser:
Ps: The whole process above is:
- 1. When we declare a script tag of type module in index. HTML, the browser issues a GET as the server does.
- 2. When the browser requests the main.js file and detects the package imported by import, it will initiate an HTTP request to obtain the content file of the module from its internal import reference.
- 3, Vite’s main function is through the browser hijack the requests, and corresponding processing in the back-end will be used in the project file with a simple decomposition and integration, and then returned to the browser, not the packaging on file compiling Vite the process, so its running speed than the original webpack development compilation speed a lot!
As you can see, 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.
Of course what you can see in Vite1.x is
import { createApp } from "/@modules/vue.js"
Copy the code
3.3 defineConfig Definable types
import { defineConfig } from 'vite'
export default defineConfig({
// ...
})
Copy the code
or
export default ({ command, mode }) => { if (command === 'serve') { return { // serve specific config } } else { return { // build specific config } }}Copy the code
3.4 the CSS file
-
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
<style module> </style> ``` Copy the code
4. Changes of Vite2
- Configuration options changes: VUe-specific options, introduction changes, we see during installation: create type, CSS options, JSX options, etc.
- Alias changes: No longer required
/
Beginning or ending - Vue support: Yes
@vitejs/plugin-vue
Separate plug-in support - The react to support
- HMR API changes
- List format changes
- Plug-in API redesign
5. Vite configuration
For more details on vite configuration, see vitejs.cn/config/
5.1 Alias Configuration
Add it in vite. Config. ts
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import {resolve} from "path" // https://vitejs.dev/config/ export default defineConfig({ resolve: { alias: { "@": resolve(__dirname,"src"), "comps": resolve(__dirname,"src/components"), "apis": resolve(__dirname,"src/apis"), "views": resolve(__dirname,"src/views"), "utils": resolve(__dirname,"src/utils"), "routes": resolve(__dirname,"src/routes"), "styles": resolve(__dirname,"src/styles"), }, }, plugins: [vue()], server: { host: "0.0.0.0" // Network: use --host to expose}})Copy the code
You can see that the alias is configured with the/removed
☞ PS: We want to use the alias @ for the ts field in the. Vue
You also need to configure ts.config.json
{
"compilerOptions": {
"target": "esnext",
"useDefineForClassFields": true,
"module": "esnext",
"moduleResolution": "node",
"strict": true,
"jsx": "preserve",
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"lib": ["esnext", "dom"],
"baseUrl": ".",
"paths": {
"@/*":["src/*"]
}
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
"exclude": ["node_modules"]
}
Copy the code
5.2 CSS configuration
CSS: {postcss: ", // Inline postCSS configuration (format same as postcss.config.js), or a custom postCSS configuration path (default based on the project root directory). PreprocessorOptions: {// Specify the options passed to the CSS preprocessor SCSS: {// global SCSS, put multiple domains, such as: theme variables, and some mixed etc. // additionalData: `@import "src/styles/index.scss"; `, javascriptEnabled: true, }, }, },Copy the code
5.3 Some packaging configurations: esbuild
Q&a time:
🙋 Q: Why can’t my viet.config. ts directly reference the path module
A: We need to install the module dependency NPM install @types/node –save-dev