惊讶,Vite 原来也可以跑在浏览器

为大家介绍一个 vite 的一个终端插件,使之可以运行在浏览器中。它就是# vite-plugin-terminal

Git 地址:github.com/patak-dev/v...

vite-plugin-terminal

这个插件使用起来很简单,首先安装:

js 复制代码
npm i -D vite-plugin-terminal

然后将插件添加到您的 vite.config.ts 配置中:

js 复制代码
// vite.config.ts
import Terminal from 'vite-plugin-terminal'

export default {
  plugins: [
    Terminal()
  ]
}

最后,你可以在源代码中像使用 console.log 一样使用它。

js 复制代码
import terminal from 'virtual:terminal';
import './module.js';

terminal.log('Hey terminal! A message from the browser');

const json = { foo: 'bar' };

terminal.log({ json });

terminal.assert(true, 'Assertion pass');
terminal.assert(false, 'Assertion fails');

terminal.info('Some info from the app');

terminal.table(['vite', 'plugin', 'terminal']);

看看效果。

体验地址:stackblitz.com/edit/github...

将日志导入终端

如果您希望标准 console 日志出现在终端中,您可以使用以下 console: 'terminal' 选项 vite.config.ts:

js 复制代码
// vite.config.ts
import Terminal from 'vite-plugin-terminal'

export default {
  plugins: [
    Terminal({
      console: 'terminal'
    })
  ]
}

在这种情况下,就不需要导入虚拟终端来使用该插件。

js 复制代码
console.log('Hey terminal! A message from the browser')

如果想要更多控制,也可以手动在脑海中覆盖它。

js 复制代码
  <script type="module">
    // Redirect console logs to the terminal
    import terminal from 'virtual:terminal'
    globalThis.console = terminal
  </script>

双端控制台

如果希望同时控制登录终端和控制台,可以使用 output 选项来定义 terminal 应记录日志的位置。接受 terminal、console 或同时包含两者的数组。

js 复制代码
// vite.config.ts
import Terminal from 'vite-plugin-terminal'

export default {
  plugins: [
    Terminal({
      output: ['terminal', 'console']
    })
  ]
}

其他

这个插件方法非常多,基本和 console 一样。

js 复制代码
terminal.log(obj1 [, obj2, ..., objN])
terminal.info(obj1 [, obj2, ..., objN])
terminal.warn(obj1 [, obj2, ..., objN])
terminal.error(obj1 [, obj2, ..., objN])
terminal.assert(assertion, obj1 [, obj2, ..., objN])
terminal.group()
terminal.groupCollapsed()
terminal.groupEnd()
terminal.table(obj)
terminal.time(id)
terminal.timeLog(id, obj1 [, obj2, ..., objN])
terminal.timeEnd(id)
terminal.clear()
terminal.count(label)
terminal.countReset(label)
terminal.dir(obj)
terminal.dirxml(obj)

也可以定制一些配置。 例如上面介绍到的 console,设置为 'terminal' 使其 globalThis.console 等于terminal 应用程序中的对象。设置 output,定义日志的输出位置。设置 strip,terminal.*()生产时捆扎时剥去。还可以设置 includeexclude 用来指定插件在删除生产调用时应在构建中操作的文件和指定插件在删除生产调用时应忽略的构建中的文件。

小结

# vite-plugin-terminal 换种方式颠覆了现在大多人本地开发的模式,如果用来快速做演示 demo,是一个非常不错的选择。但是当前这个插件还是存在不少的问题,不过真的要用在大型商业项目里面时候,就要考虑跟 Devops系统的集成,希望# vite-plugin-terminal完全成熟开源后,能给开发者带来更多的便利。

参考

相关推荐
Vicky&James12 分钟前
WPF到Web的无缝过渡:英雄联盟客户端项目OpenSilver迁移实战
前端·wpf
m0_7482336416 分钟前
RabbitMQ 进阶
android·前端·后端
不想有bug的小菜鸟24 分钟前
vue3使用iframe全屏展示pdf效果
前端·pdf
m0_7482386325 分钟前
Spring Boot项目接收前端参数的11种方式
前端·spring boot·后端
u01005596026 分钟前
前端代理,解决跨域问题讲解
前端
quitv31 分钟前
react脚手架配置别名
前端·javascript·react.js
m0_5287238139 分钟前
前端如何进行性能优化
前端·性能优化
化作繁星41 分钟前
在 Vue 3 中,如何缓存和复用动态组件
前端·vue.js·缓存
一粒沙-1 小时前
iOS 将GIF图分享至微信
前端·ios
graywen1 小时前
从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
前端