This article was posted this month, but deleted due to inappropriate language and poor consideration. I would like to apologize again to the author of Volar. I have been in touch with the author to express my apologies. After the article joke will think twice, I hope you understand.
The previous inappropriate remarks have been deleted.
“Jia Hao, the new H5 project to Vite whole?” , hearing this, Webpack destroyed for a long time I left tears of happiness 💧
To be clear, our H5 project is small and can only be opened by SMS link. For small projects like this, it’s great to practice some new posture techniques, so don’t blindly follow suit!
Vite
First of all, how do you pronounce the word Vite?” Crooked? V,? Victor? “
To that, too, the first sentence of the official document makes a contribution: Vite (French word for “fast”, pronounced /vit/), too! Seeing the name Vite, it feels like Utah wants to create its own V-universe.
The Run up to 🏃 came ️
Vite provides handy tools for initializing projects:
yarn create @vitejs/app project-name --template vue-ts
Copy the code
First of all, Vite is just a packaging tool, just like Webpack/Rollup/Parcel, which means Vite isn’t strongly Vue related, nor is React. Once the project is created, you can run the yarn serve command to run the local dev environment:
{
"scripts": {
"dev": "vite".// start dev server
"build": "vite build".// build for production
"serve": "vite preview" // locally preview production build}}Copy the code
Developers who use Webpack regularly will know that it takes eight or nine seconds to launch a local dev environment, but Vite is fast.
Imperial jade liquor, 180 cups. Why so fast? Listen to me blow… You’ve probably all heard of a company CTO who’s obsessed with open source and has written a fast flying (I’d like to call it the fastest man in the world) package called Esbuild. Vite is the esbuild used when launching the local development environment:
// vite/dist/node/chunks/dep-1bdbec90.js
/ / line 68134
async function createServer$2(inlineConfig = {}) {
// ...
const server = {
// ...
transformWithEsbuild, / / line 68168
// ...
};
}
/ / line 26715
async function transformWithEsbuild(code, filename, options, inMap) {
const service = await ensureService();
try {
// ...
const result = await service.transform(code, resolvedOptions); / / line 26735
// ...
} catch {
// ...}}/ / line 26702
async function ensureService() {
if(! _servicePromise) { _servicePromise =require('esbuild').startService();
}
return _servicePromise;
}
Copy the code
This is the order in which the vite serve command is invoked, and it ends up in the startService method of esbuild. U1s1, fast is something that developers can experience, but users can’t perceive, so it doesn’t matter how fast you start your development and how big the package is. So, for now, development is about “small and fast”!
The configuration of code compression is described in the official documentation:
- build.minify
- Type: boolean | 'terser' | 'esbuild'
- Default: 'terser'
- Set to false to disable minification, or specify the minifier to use. The default is Terser which is slower but produces smaller bundles in most cases. Esbuild minification is significantly faster, but will result in slightly larger bundles.
Copy the code
By default, terser is used for compression, but if you feel a bit slow, you can set it to esbuild. The downside is that esbuild compression will be larger. Therefore, IT is recommended to use Terser, after all, the products are for users to use in production environment. But the build uses rollup:
// vite/dist/node/chunks/dep-1bdbec90.js
/ / line 46730
var build$1 = {
// ...
build: build, / / line 46734
};
/ / line 46446
async function build(inlineConfig = {}) {
// ...
try {
return await doBuild(inlineConfig); / / line 46449
}
finally {
// ...}}/ / line 46459
async function doBuild(inlineConfig = {}) {
// ...
const rollup = require('rollup'); / / line 46501
try {
const bundle = await rollup.rollup({
// ...
});
}
catch {
// ...}}Copy the code
In the doBuild method, SSR packaging is also processed. Interested readers can read the vite source code (has been carefully marked with the specific number of lines).
Add brickJavaAdd tile 🧱
The project created by following the above command only supports Vue and TS. If you need to support more features, you need to configure them by yourself. We will explain in detail below.
Router
Vue 3 Composition API was used in the project, so Vue Router 4+ was used:
yarn add vue-router@4
Copy the code
Lazy loading using dynamic import:
export const routes = [
{ path: '/'.component: () = > import('@/pages/home/home.vue')},// ...
// other pages
{ // 404 page
path: '/:pathMatch(.*)*'.component: () = > import('@/pages/not-found/not-found.vue'),},];Copy the code
The use in main.ts is also slightly different from Vue 2+ :
import { createApp } from 'vue';
import { createRouter, createWebHistory } from 'vue-router';
import { routes } from './routes';
import App from './app.vue';
const app = createApp(App);
const router = createRouter({
history: createWebHistory(),
routes,
});
app.use(router);
app.mount('#app');
Copy the code
CSS Preprocessors
In general, today’s projects will use Less or Scss instead of CSS directly. If you want to use a preprocessor language, you can simply install the dependency of the corresponding preprocessor language without further details. And in use with the usual use is no different:
<style lang="less">
/* Your less code */
</style>
Copy the code
But sometimes we might define some variables or mixins that are used globally. In this case, we often use additionalData like less-loader to introduce the corresponding global file in the header of each style file. To avoid writing @import “@/styles/mixins.less” statements in each file, the same is true with Vite:
export default defineConfig({
css: {
preprocessorOptions: {
less: {
additionalData:
'@import "@/styles/variables"; \n@import "@/styles/mixins"; \n',},},},});Copy the code
Using CSS. PreprocessorOptions. Less. AdditionalData can be realized, does not need to install a pack need to install all kinds of loader, simple ~
Alias
In fact, Vite and Webpack have similar configuration methods, but the speed is far different (Webpack curts out of the studio). For example, to improve the development experience, we would configure a path shorthand that maps/SRC to something like @ :
export default defineConfig({
resolve: {
alias: {
'@': '/src',
dayjs: 'dayjs/esm',
},
},
});
Copy the code
As with Webpack, you can configure the resolve.alias field directly in viet.config. ts and then in tsconfig.json:
{
"compilerOptions": {
"paths": {
"@ / *": ["./src/*"]}}}Copy the code
Dayjs is used in the project. In the above example, the dayjs/index.js path from the original dayJS dependency was manually changed to dayjs/ ESm /index.js (ESModule).
Proxy
Vite also provides corresponding fields to configure proxy and static resource access paths:
export default defineConfig({
base: 'Static resource URL'.server: {
proxy: {
'/api': {
target: 'the request URL'.changeOrigin: true,},},},})Copy the code
Needless to say, DDDD! It is worth noting that we used to get environment variables through process.env.node_env, but in Vite we moved it to import.meta.env. To continue, add to NPM script:
{
scripts: {
"start": "NODE_ENV=development vite"}}Copy the code
Assets
There are a lot of SVG ICONS added to the project. Of course SVG can be displayed as , but more often we will import it as a string via raw-loader. In Vite, you can add? Raw way to introduce strings:
import Icon from '@/assets/icon.svg? raw';
Copy the code
The result is an XML string from SVG, which is displayed in V-HTML. Vite comes with raw loader without additional installation.
Postcss
Vite also comes with Postcss 8+, so just add the corresponding postcss.config.js file to the project root directory. However, some Postcss plug-ins use older versions of the API (such as the postCSs-px-to-viewport we use). This will print a warning on the console, but it does not prevent use.
What’s more
Although Vite has been released in two major versions, it is still updated very quickly, some content versions are still updated frequently, some are tinkering:
For example, Vite only supports ES2015; The test environment of Vue 3 still does not work after being configured according to its documentation. In the future, you need to continue to pay attention to the relevant configuration of the test.
Vue 3 type checking has always been a big problem. We can’t do it directly with TSC, but we can do it at development stage with a VSCoder plugin named Volar:
During development, the plug-in will underline any type errors, and you can also run verifyAllScripts to check the types of all files. So I thought: what if we could run verifyAllScripts directly from the command line?
The reality is harsh, but the authors say tools are being developed. Say the author also is really efficient! When I spoke to the author on the morning of March 2nd, this tool was still under development and was released after a nap! Once installed in your project, simply run VUE-TSC for type checking! Configured in Husky or Lint-staged, this is great!
End
Overall, Vite meets most of your development needs, and the experience is pretty good. It doesn’t require a lot of configuration and scripting like Webpack/Rollup etc. It’s pretty much out of the box and a lot faster than the Parcel I used to use. Interested developers can still give it a try, but think twice about using it for a production project! After all, the new appointee still has to experience the test of time