vite是初体验
开始使用vite前,先了解一些基本概念。
vite脚手架和vite的区别
yarn create vite 命令会做什么
- 在全局安装create-vite(vite的脚手架),帮我们做一系列的预设。
- 运行 create-vite下的bin目录下的执行配置
误区:会认为是vite在做的事情,实际是create-vite在做的,它内置了vite
预设:下载vite、vue、postcss、less、babel,直接给一套模板,做好了最佳实践的配置
vite启动项目
vite是开箱即用(out of box):不需要任何配置即可使用。
1. 创建项目yarn init -y. 不使用vite
项目目录
├─counter.js
├─index.html
├─main.js
├─package.json
└yarn.lock
counter.js
export const counter = 0;
main.js
import { counter } from "./counter.js"; // 必须加后缀
import _ from "lodash";
console.log("打印***counter", counter);
console.log("打印***_", _);
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script src="./main.js" type="module"></script>
</body>
</html>
在默认情况下,我们的esm去导入资源时候,要么是绝对路径,要不是相对路径,否则会报错。
问题: 为什么es官方在导入非绝对路径或者非相对路径时,不帮我们去搜索node_modules?假如浏览器做了这件事?会发生什么情况。
如果这样做会将lodash所依赖的又进行下载,会形成依赖图,网络进行下载,会非常消耗性能。commonJs可以,因为是运行在服务端,本身找node_modules不是通过网络请求,直接读取本地文件。
2. 使用vite
yarn add vite -D
// package.json
"scripts": {
"dev": "vite"
},
"dependencies": {
"lodash": "^4.17.21"
},
"devDependencies": {
"vite": "^4.1.4"
}
运行yarn dev ,lodash可以正常加载