AIFeed

Civet:更重类型、更少打字的 TypeScript 超集

Translation(model translation, not the source's own text)

Civet

编写 TypeScript 的现代方式。

  • 文档
  • 设计理念
  • Civet Playground
  • Civet VSCode 扩展
  • Discord 服务器
  • 适用于 Vite、esbuild、Astro、Farm、Rolldown、Rollup、Webpack、ESM/CJS loader、Babel、Jest、Gulp、Bun、<script> 标签的插件
  • 适用于 Solid(旧版)和 Solid Start 的起始模板

快速开始指南


        # Install
npm install -g @danielx/civet
# Run Civet code directly in a REPL
civet
# Transpile typed Civet code into TypeScript in a REPL
civet -c
# Compile Civet source file to TypeScript
civet < source.civet > output.ts
# Execute a .civet script
civet source.civet ...args...
# Execute a .civet source file in node
node --import @danielx/civet/register source.civet
# Type check entire project, which requires TypeScript installed
npm install -g typescript
civet --typecheck
      
image
image

代码示例


        ts, {CompilerOptions} from typescript

DefaultCompilerOptions : CompilerOptions :=
  allowNonTsExtensions: true
  allowJs: true
  target: ts.ScriptTarget.Latest
  moduleResolution: ts.ModuleResolutionKind.NodeJs
  module: ts.ModuleKind.CommonJS
  allowSyntheticDefaultImports: true
  experimentalDecorators: true

fileCache : Record<string, any> := {}

createCompilerHost := (options: CompilerOptions, moduleSearchLocations : string[]) ->
  fileExists := (fileName: string) : boolean ->
    fileCache[fileName]?

readFile := (fileName: string) ->
    fileCache[fileName]
      

概述

Civet 本质上是一个优雅的 TypeScript 超集。

新特性与提案中 ES 特性的实现

请参阅文档以了解这些特性及其他特性的示例。

  • 模式匹配(基于 TC39 提案)switch 可以匹配像 [{type: "text", name}, ...rest] 这样的模式
  • switch 可以匹配像 [{type: "text", name}, ...rest] 这样的模式
  • 管道操作符(基于 F# pipes、Hack pipes 和 TC39 提案)data |> Object.keys |> console.log 等价于 console.log(Object.keys(data)) 使用单参数箭头函数或 & 简写来指定如何使用左侧 |> await、|> yield 和 |> return(位于末尾)用于将左侧包裹在该操作中
  • data |> Object.keys |> console.log 等价于 console.log(Object.keys(data))
  • 使用单参数箭头函数或 & 简写来指定如何使用左侧
  • |> await、|> yield 和 |> return(位于末尾)用于将左侧包裹在该操作中
  • 短函数块语法,类似 Ruby 的 symbol to proc、Crystal、Elm 记录访问 访问:x.map &.name 或 x.map .name → x.map(a => a.name) 嵌套访问 + 切片:x.map &.profile?.name[0...3] → x.map(a => a.profile?.name.slice(0, 3)) 函数调用:x.map &.callback a, b → x.map($ => $.callback(a, b)) 一元操作符:x.map !!& → x.map($ => !!$) 二元操作符:x.map &+1 → x.map($ => $+1)
  • 访问:x.map &.name 或 x.map .name → x.map(a => a.name)
  • 嵌套访问 + 切片:x.map &.profile?.name[0...3] → x.map(a => a.profile?.name.slice(0, 3))
  • 函数调用:x.map &.callback a, b → x.map($ => $.callback(a, b))
  • 一元操作符:x.map !!& → x.map($ => !!$)
  • 二元操作符:x.map &+1 → x.map($ => $+1)
  • 对象字面量简写 {foo()} → {foo: foo()}, {props.foo} → {foo: props.foo} {${x}${y}: z} → {[${x}${y}]: z} data.{x,y} 或 data{x,y} → {x: data.x, y: data.y} 基于 LiveScript 的标记简写:{+debug, -live, !verbose} → {debug: true, live: false, verbose: false}
  • {foo()} → {foo: foo()}, {props.foo} → {foo: props.foo}
  • {${x}${y}: z} → {[${x}${y}]: z}
  • data.{x,y} 或 data{x,y} → {x: data.x, y: data.y}
  • 基于 LiveScript 的标记简写:{+debug, -live, !verbose} → {debug: true, live: false, verbose: false}
  • 来自任意双参数函数的自定义中缀操作符
  • do 表达式、if 表达式、for 表达式

ES6+ 特性的便利性

  • 常量赋值简写:a := b → const a = b, {a, b} := c → const {a, b} = c

文章标题:Civet:更偏向类型、更少打字的 TypeScript 超集

正文:

  • let 赋值简写:a .= b → let a = b
  • 以上写法的带类型版本:a: number .= 5 → let a: number = 5(但注意 a: number = 5 会得到对象字面量 {a: (number = 5)})。
  • @#id → this.#id 私有标识符简写
  • import 简写:x from ./x → import x from "./x"
  • 动态 import 简写:不在顶层的 import './x'(例如 await import './x' 或在函数内部)→ import('./x')
  • 可选的 import 重命名语法,对应解构重命名:import {x: y} from "./z" → import {x as y} from "./z"。你仍然可以使用 as 来兼容现有的 ES import。
  • export 简写:export x, y → export {x, y}
  • 三反引号模板字符串会去除前导缩进,以提升可读性
  • 类构造函数简写 @( ... )
  • ClassStaticBlock @ { ... }
  • < 作为 extends 的简写
  • /// 块状 RegExp,类似 Python 的 re.X

JSX 增强

灵感来自 solid-dsl 的讨论和 jsx 规范 issue

  • 缩进:无需显式闭合 <tag> 或 <>,你可以缩进子元素,Civet 会替你闭合标签
  • 多个相邻元素和/或片段会自动合并为一个片段。
  • 箭头函数子元素不需要用花括号包裹(假设它们前面没有文本);这是无歧义的,因为 > 不是合法的 JSX 文本。例如,<For> (item) => ...(函数体可以缩进)。
  • #foo 是 id="foo" 的简写;还有 #"foo bar"、#foo ${bar}、#{expr}
  • .foo 是 class="foo" 的简写(但标签名后必须至少有一个空格);还有 .foo.bar、."foo bar"、.foo ${bar}、.{expr}
  • "civet react" 标志使用 className 而不是 class
  • +foo 是 foo={true} 的简写,-foo/!foo 是 foo={false} 的简写
  • 任何带花括号的对象字面量都可以用作属性:{foo} → foo={foo},{foo: bar} → foo={bar},{...foo} 保持不变;方法和 getter/setter 也可以使用。
  • 属性 ...foo 是 {...foo} 的简写
  • 属性值若不含空白或已适当包裹(带括号的表达式、字符串和模板字符串、正则表达式、数组字面量、带花括号的对象字面量),则无需花括号:foo=bar → foo={bar},count=count() → count={count()},sum=x+1 → sum={x+1},list=[1, 2, 3] → list={[1, 2, 3]}
  • 属性可以使用计算属性名:[expr]={value} → {...{[expr]: value}}
  • "civet solid" 标志会为 JSX 元素和片段添加正确的类型。使用 "civet solid client"(默认)表示仅客户端代码,使用 "civet solid server" 表示仅服务端代码(仅 SSR),或使用 "civet solid client server" 表示在客户端和服务端运行的同构代码(SSR + hydration)。
  • XML 注释:<!-- ... --> → {/ ... /}

TypeScript 增强

  • 自动将 import 中的 .[mc]ts 改写为 .[mc]js(针对 microsoft/TypeScript#37582 的变通方案)
  • := readonly 类字段初始化器 class A x := 3 class A { readonly x = 3 }

        class A
    x := 3
      

        class A {
    readonly x = 3
  }
      
  • 提案:类型化解构
  • 提案:类型的点号表示法
  • 提案:模块接口 microsoft/TypeScript#38511
  • TODO:类型声明简写

相对 ES6 的变化

  • 隐式返回,即使是多语句函数也适用(可以通过指定 void 返回类型、添加尾随 ; 或显式 return,或通过指令 "civet -implicitReturns" 来避免)
  • 单参数箭头函数不允许省略括号。x => ... 必须写成 (x) => ...。理由是:在 CoffeeScript 中 x -> ... 会变成 x(function() ...),而让 -> 和 => 的行为比现在差异更大是不好的。向应用传递匿名函数时省略括号也很方便。
  • for(i of x) ... 默认使用 const 声明 → for(const i of x) ...
  • 条件语句和许多其他位置不允许逗号运算符。if x, y 不被允许。但 for i = 0, l = a.length; i < l; i++, i *= 2 是允许的。
  • case/when 中的逗号运算符会变成多个条件。

Civet:更重视类型、更少打字的 TypeScript 超集

  • 数字不能以点结尾(否则会与 CoffeeScript 的切片 y[0..x] 产生歧义)。这也意味着你不能用 1..toString() 访问数字的属性,请改用 1.toString()。当指数前出现点时,它会被当作属性访问,因为指数可能是一个合法的属性名 1.e10 → 1..e10。解决办法是在末尾补零 1.0e10,或去掉指数前的点 1e10。
  • 额外的保留字 and、or、loop、until、unless
  • 实验性的装饰器语法使用 @@ 而不是 @,因为 @ 是极其宝贵的字符资源,@id → this.id,而且 @ 还用于静态字段/方法等。@@classDecorator class X @@methodDecorator method() {}

        @@classDecorator
class X
  @@methodDecorator
  method() {}
      
  • 在 switch 中会自动 break 并添加块级作用域。
  • switch 中的 else 会添加块级作用域。
  • 一元运算符与操作数之间不能有空格。条件与三元运算符 ? 之间必须有空格,例如 x ? a : b,因为 x? 是一元存在性运算符。
  • 标签写作 :label(特殊情况 $: 除外,用于 Svelte)

脚本化改进

  • Shebang 行在输出中保持不变 #!./node_modules/.bin/ts-node console.log "hi"

        #!./node_modules/.bin/ts-node
console.log "hi"
      

与 CoffeeScript 的比较

看看这份详细的 Civet // CoffeeScript 对比

指令

Civet 不只是一门语言;它可以通过指令以多种方式进行配置,以添加或移除语言特性,或改善某些环境中的行为。参见配置文档。

在 Node.js 环境中使用 Civet

你现在已经被说服,Civet 适合你当前/下一个项目。以下是如何设置你的环境,以便立刻提高效率并拥有美好时光℠。

测试

借助 c8 的 source map 集成和 Civet 的 source map,代码覆盖率“开箱即用”。

c8 + Mocha

package.json


        "scripts": {
    "test": "c8 mocha",
    ...
  },
  "c8": {
    "extension": [
      ".civet"
    ]
  },
  "mocha": {
    "extension": [
      "civet"
    ],
    "loader": [
      "@danielx/civet/esm"
    ],
    ...
  ...
      

如果你不在乎代码覆盖率,可以跳过 c8(但它这么简单,何不保留呢?)。

如果你想混搭,也可以添加 .js 和 .ts 扩展名!如果你 require coffeescript/register 或为它添加一个 loader,甚至连 .coffee 也能用。

执行测试

第 4 步:享受!

开发

使用 Civet Language Server 的 alpha 版本

语言服务器提供语法高亮、补全、悬停文档、符号大纲、红色波浪线和跳转到定义。

问?为什么我不能直接用 VSCode 内置的 TypeScript LSP?

答:VSCode 内置的 TypeScript LSP 无法解析非 .ts/.js 文件,即使装了插件也不行。也许有一天他们会允许插件调整解析器并插入一个转译步骤,但在那之前,单独的语言服务器是必要的。

问?有时候文件大纲消失了,红色波浪线全都在错误的位置,也许还会弹出一个关于某种 LSP 错误的通知。

答:很抱歉发生了这种事,但 Civet Language Server 仍处于 alpha 阶段,正在快速改进。请告诉我具体发生了什么,下次我会努力做得更好。

这可能在你的 Civet 文件存在语法错误时发生。与此同时,你可以用 CLI 工具检查它是否能编译。

请务必提交 bug 报告 / 功能请求。

构建

我强烈建议使用 esbuild 来构建 / 打包你的 Civet 项目。


        import esbuild from 'esbuild'
import civetPlugin from '@danielx/civet/esbuild'

esbuild.build({
  ...,
  plugins: [
    civetPlugin({ ts: 'preserve' })
  ]
}).catch(() => process.exit(1))
      

它超级快,而且效果很好!

赞助

如果你愿意,可以在 Open Collective 上赞助 Civet。

The translation is machine-generated and individual terms may be off. Nothing is rewritten or cut; the original is authoritative.

Published by Hacker News
This site only summarises and aggregates; copyright stays with the original author. Headlines and summaries follow the source — where they differ, the original wins.
Read the original ↗