preface
As we all know, [email protected] integrated modular tool is Webpack, but also the enterprise with a more popular, mature modular management tools, so in addition to Webpack, more popular modular tools and Snowpack, Vite.
Weback: Snowpack:
- They both have loader processors that parse the CSS, but do not directly generate a separate CSS file (attached)
mini-css-extract-plugin
Instead, load a JS module and insert the CSS text into the page as the content of the style tag via the DOM API:= generate a dynamic node in index. HTML Style: text/CSS - Generate JS resources (CSS, images…) Will add
proxy
throughtransformEsimports
This method can be put into jsimport
Module path conversion,node modules
Replace withwebmodules
.wrapEsmProxyResponse
Generate the Proxy module method,HMR: hot Module Replacement
(Hot module replacement) - The HMR code is placed
assets/hmr.js
One of them is: Webpack adds to the pagescript
TAB to load Snowpack using nativedynamic import
To load the
Similar to Snowpack, Vite is a packageless build tool that imports code using es Module for development and builds in rollup for production. Also have:
1. Cold service startup, native, no build 2. Development hot update 3. Compile on demand without DOM refresh
But here’s the difference:
- Vite is more suitable for use with VUe3.0 (not compatible with Vue2.0), which is more ecologically integrated, but it is a relatively new module tool (as can be seen from compatibility), so there are many holes and need to be optimized, so it is not recommended for use in actual enterprise development
- Snowpack is now available with V2 and forward compatible V1 on Vue, React, Preact and Svelte
The installation of vite
$ npm init vite-app <project-name>
$ cd <project-name>
$ npm install
$ npm run dev
Copy the code
The code analysis
The key change isindex.html
In the import file import mode
This allows you to organize your code in main.js using ES6 ModulesThe 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.
Resource analysis
Importing CSS Files
In our program, most styles exist in the SFC in form except for global styles
CSS Module JS importCSS Module
: Name the CSS file as*.module.css
Can be CSS preprocessorInstall 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 the postcss.config.js file.
module.exports = {
plugins: [
require('autoprefixer')]}Copy the code
NPM I postcss [email protected]
Resource URL processing
- Reference static resources *We can do it atTemplate, style, and pure. CSS files reference static resources in relative and absolute paths. ** (This is so cool!!)
<! -- 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
- Public directory
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
> Note that references to files placed under 'public' need to use absolute paths. For example, 'public/icon. PNG' should use '/icon. PNG' referencesCopy the code
Typescript integration
Vite can be imported directly into. Ts files and used in SFC via
<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
The project root directory creates vite. Config. js, and you can deeply configure the Vite project.
Proxy (also a major concern during development)
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
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
The code is read
import.meta.env.VITE_TOKEN
Copy the code
Packaging and deployment
-
packaging
Use NPM run build to perform packaging
-
The deployment of
Manual uploading of dist to the server and configuring nGINx is certainly possible, but it can also be automated to avoid the previous tedious operations. Github Actions can be used to implement THE CI/CD process. I will not go into details here, but you can find relevant information and try to practice it.
Relevant literature
Snowpack principle: www.ershicimi.com/p/6fa366fea… Know snowpack:zhuanlan.zhihu.com/p/108222057
Welcome to my blog: juejin.cn/user/246754…
Github address: github.com/NurTuam
Lots of support! I will continue to update ❤️