展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

依赖预构建

  • vite在生产和开发环境打包的不同
yarn dev ---> 开发(每次依赖预构建所重新构建的相对路径都是正确的)
vite会全权交给一个叫做rollup的库去完成生产环境的打包
  • 在上1篇博客中,提到vite不会帮我们自动引入绝对路径和非绝对路径的依赖
# 这是因为,如果引入1个如下的依赖
import _ from "lodash";
# lodash可能也import了其他的东西
# 在处理的过程中如果说看到了有非绝对路径或者相对路径的引用, 他则会尝试开启路径补全
import _ from "/node_modules/.vite/lodash"; // lodash可能也import了其他的东西
import __vite__cjsImport0_lodash from "/node_modules/.vite/deps/lodash.js?v=ebe57916";
# 找寻依赖的过程是自当前目录依次向上查找的过程, 直到搜寻到根目录或者搜寻到对应依赖为止 /user/node_modules/lodash, ../
# 最终导入的依赖会特别多
  • 依赖预构建
首先vite会找到对应的依赖, 然后调用esbuild(对js语法进行处理的一个库), 将其他规范的代码转换成esmodule规范,
然后放到当前目录下的node_modules/.vite/deps, 同时对esmodule规范的各个模块进行统一集成
# 例如源代码如下
export default function a() {}
# 经过esbuild处理后
export { default as a } from "./a.js"
# vite重写以后
function a() {}
  • 代码案例

  • 新建1个文件夹

  • 编写counter.js

export const count = 0;
  • 编写main.js
import { count } from "./counter.js";
console.log("count")
  • 编写index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
</head>
<body>
<script src="./main.js" type="module"></script>
</body>
</html>
  • 初始化
npm init -y
# 安装vite
yarn add vite -D
# 配置package.json
"scripts": {
"dev": "vite"
},
# 安装lodash-es
yarn add lodash-es
# counter.js中打印
import _ from "lodash-es";
console.log("lodash-es", _);
# 启动项目
yarn dev
  • vscode中按住ctrl,查看lodase-es
export { default as add } from "./add";
export { default as after } from "./after";
export { default as ary } from "./ary";
export { default as assign } from "./assign";
export { default as assignIn } from "./assignIn";
export { default as assignInWith } from "./assignInWith";
export { default as assignWith } from "./assignWith";
export { default as at } from "./at";
export { default as attempt } from "./attempt";
export { default as before } from "./before";
export { default as bind } from "./bind";
export { default as bindAll } from "./bindAll";
export { default as bindKey } from "./bindKey";
export { default as camelCase } from "./camelCase";
export { default as capitalize } from "./capitalize";
export { default as castArray } from "./castArray";
export { default as ceil } from "./ceil";
export { default as chain } from "./chain";
export { default as chunk } from "./chunk";
export { default as clamp } from "./clamp";
export { default as clone } from "./clone";
......
  • 启动项目后,查看lodash-es

  • 发现源代码不一样,这是因为使用了依赖预构建

  • 新建vite.config.js,将lodase-es排除依赖预构建

export default {
optimizeDeps: {
exclude: ["lodash-es"],
}
}
  • 再次查看,发现和源码一样了
posted @   DogLeftover  阅读(91)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示