[Tools] Vite intro

news/2025/2/4 2:10:08/文章来源:https://www.cnblogs.com/Answer1215/p/18697929

Overview

为什么选Vite: https://cn.vite.dev/guide/why.html

 

esbuild, Rollup: https://cn.vite.dev/guide/why.html#why-bundle-for-production

 

Quick start

1. Start a new project

pnpm init

2. installl Vite, Typescript

pnpm add vite typescript -D

3. create index.html under root directory

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body><div id="app"></div>
</body>
<script type="module" src="./src/index.ts"></script>
</html>

4. Create src/index.ts, src/counter.ts

// index.ts
import { setupCounter } from "./counter";document.querySelector('#app')!.innerHTML = `<div><button id="counter" type="button"></button></div>
`;
setupCounter(document.querySelector('#counter') as HTMLButtonElement);// counter.ts
export function setupCounter(element: HTMLButtonElement) { let counter = 0;const setCounter = (count: number) => { counter = count;element.innerHTML = `Counter: ${counter}`;}setCounter(0);element.addEventListener('click', () => setCounter(counter + 1));
}

5. Update package.json

  "scripts": {"dev":"vite","build":"vite build","preview":"vite preview"},"type": "module",

6. Run pnpm run dev 

Then a web applicaiton should be start.

 

默认配置和一些常识问题

1. Create tsconfig.json
Recommend to include following options, see from https://cn.vite.dev/guide/features.html#typescript-compiler-options

{"compilerOptions": {"target": "ES2020","module": "ESNext","lib": ["DOM", "DOM.Iterable", "ESNext"],"isolatedModules":true,"useDefineForClassFields":true,"skipLibCheck": true,"moduleResolution": "Bundler","esModuleInterop": true,"allowSyntheticDefaultImports": true,"resolveJsonModule": true,"noEmit": true,"allowImportingTsExtensions": true},"include": ["src","vite.config.ts"]
}

2. Create vite.config.ts

Tell the port and open the browser

import { defineConfig, ConfigEnv, UserConfig} from 'vite'export default defineConfig(({command, mode}: ConfigEnv):UserConfig => { console.log(command); console.log(mode); // development, production, useful when you want to run different code based on the commandreturn {server: {port: 3000,open: true, // open the browser (true), or you can tell which html should be the entry, e.g. index1.html}}
})

 3. ts声明问题

for example added following code in vite.config.ts

// ...
import path from "path"// ...

Typescript complain that Cannot find module 'path' or its corresponding type declarations.

This is due to it is running in node.env

Run: pnpm add @types/node -D will resolve the issue

 4. node环境ESM问题

without type: "module"in package.json, if we run node src/test1.jswill throw SyntaxError: Cannot use import statement outside a module

// test1.js
import test2 from "./test2";
test2();//test2.js
export default function test2() { console.log('test2');
}

"type: module": is to resolve this issue.

5. 文件执行环境问题 & 路径查找问题

But running node test1.jsagain, you will see Did you mean to import "./test2.js"?

If we change 

import test2 from "./test2.js"; then it works.
 
 
vite.config.ts is running in node env. In node env,
import { defineConfig, ConfigEnv, UserConfig} from 'vite'

node will help to complete the file path for the module, here we say vite, node will find it in node_module automatically.

It only happens in node env, not in browser env. In Browser env, you have to give the fulll path.

 

Add lodash-es, the update test1.js as following:

import { debounce } from "lodash-es"   //bare import ESM默认不支持
import test2 from "./test2.js";test2();
debounce(() => console.log("hello"), 1000)();

Then run:  node src/test1.js, it works as expect; but if you run it in browser, it throw error:

Uncaught TypeError: Failed to resolve module specifier "lodash-es". Relative references must start with either "/", "./", or "../". 

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document index1.html</title>
</head>
<body><div id="app"></div>
</body>
<script type="module" src="./src/test1.js"></script>
</html>

 

Give the full path then it works in browser env.

// import { debounce } from "lodash-es"   //bare import ESM默认不支持
import debounce  from '../node_modules/lodash-es/debounce.js'; // 从node_modules中引入
// ...

 

Code: https://gitee.com/dev-edu/vite/tree/main/03.%E9%BB%98%E8%AE%A4%E9%85%8D%E7%BD%AE%E5%92%8C%E4%B8%80%E4%BA%9B%E5%B8%B8%E8%AF%86%E9%97%AE%E9%A2%98/vite-demo

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/878469.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

在做同城多活方案中如何实现机房之间的数据同步?

一、前言 现在是数据的时代,如何发挥数据的价值,让系统具备更多的数据处理能力。如何完善响应的数据架构。多机房建设是其中的解决策略。 二、背景 在业务初期,考虑到投入成本,很多公司通常只用一个机房提供服务。但随着业务发展,流量不断增加,我们对服务的响应速度和可用…

在 Ubuntu 22.04 上运行 Filebeat 7.10.2

环境 操作系统:阿里云 Ubuntu 22.04.3 LTS (GNU/Linux 5.15.0-83-generic x86_64) 软件版本:Filebeat 7.10.2 用户:root 运行下载从这里下载 filebeat 7.10.2。配置简单配置一下 filebeat.yml,从标准输入采集,写入到标准输出 : filebeat.inputs: - type: stdinoutput.con…

Dify AWS:0代码搭建「AI翻译中台」

0 前言 基于Dify现有能力,已能对不少业务场景提供帮助,但对一些特定诉求,还要借助其扩展机制,本文利用翻译场景举例详细说明。 1 翻译场景复杂性分析 翻译是从简单到复杂各级都存在的场景,比较简单的翻译可能一句简单 Prompt,但对复杂、效果要求较高翻译场景,可能需要一…

25.2.3小记

抽象(abstract) 1.抽象函数不需要大括号 2.抽象的函数只能包括在抽象的类中(或者说只要一个类里有一个抽象函数,那整个类就是抽象的,因为若非抽象则定义对应类的变量之后本应该可以调用name.work类似的函数,但抽象函数因为没有body所以无法调用)其中定义的变量可以管理任…

0x80070035错误怎么解决?Win11/Win10访问NAS smba共享文件夹提示无法找到路径[Path not found]

1. 问题 Win11/Win10访问NAS smba共享文件夹提示无法找到路径[Path not found]2. 解决办法 2.1 设置网络专用网络2.2 设置高级共享2.3 设置组策略-启用-不安全的来宾登录2.4 设置组策略-Microsoft网络客户端:对通信进行数字签名(始终)-改为禁用3. 验证 现在再去访问,你会发现…

DeepSeek,你是懂.NET的!

这两天火爆出圈的话题,除了过年,那一定是DeepSeek!你是否也被刷屏了?DeepSeek 是什么DeepSeek是一款由国内人工智能公司研发的大型语言模型,拥有强大的自然语言处理能力,能够理解并回答问题,还能辅助写代码、整理资料和解决复杂的数学问题。与OpenAI开发的ChatGPT相比,De…

Welcome

This is your new vault. Make a note of something, [[create a link]], or try the Importer! When youre ready, delete this note and make the vault your own.

遭受大量境外网络攻击,郭盛华公开发声支持DeepSeek

近日,据央视新闻报道,近期DeepSeek线上服务受到大规模恶意攻击。DeepSeek这次受到的网络攻击,IP地址都在美国。 世界级的电脑天才,国际知名网络安全组织东方联盟创始人《郭盛华》罕见公开发声:“支持DeepSeek!”,他还透露:“参加了DeepSeek保卫战,坚决捍卫国产AI技术的…

E96 Tarjan缩点+树上背包 P2515 [HAOI2010] 软件安装

视频链接: 参考1:D14【模板】强连通分量 Tarjan 算法 - 董晓 - 博客园 参考2:E76 树上背包 P1064 [NOIP2006 提高组] 金明的预算方案 - 董晓 - 博客园 P2515 [HAOI2010] 软件安装 - 洛谷 | 计算机科学教育新生态// Tarjan缩点+树上背包 O(n*m) #include <iostream> …