Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A TypeScript superset that favors more types and less typing

License

NotificationsYou must be signed in to change notification settings

DanielXMoore/Civet

Repository files navigation

Build StatusNPM VersionNPM DownloadsCoverage StatusDiscordOpen Collective

The modern way to write TypeScript.

Quickstart Guide

# Installnpm install -g @danielx/civet# Run Civet code directly in a REPLcivet# Transpile typed Civet code into TypeScript in a REPLcivet -c# Compile Civet source file to TypeScriptcivet< source.civet> output.ts# Execute a .civet scriptcivet source.civet ...args...# Execute a .civet source file in nodenode --import @danielx/civet/register source.civet

image

Code Sample

ts,{CompilerOptions}fromtypescriptDefaultCompilerOptions : CompilerOptions :=  allowNonTsExtensions:true  allowJs:true  target:ts.ScriptTarget.Latest  moduleResolution:ts.ModuleResolutionKind.NodeJs  module:ts.ModuleKind.CommonJS  allowSyntheticDefaultImports:true  experimentalDecorators:truefileCache :Record<string,any> :={}createCompilerHost :=(options:CompilerOptions,moduleSearchLocations :string[])->fileExists :=(fileName:string) :boolean->fileCache[fileName]?readFile :=(fileName:string)->fileCache[fileName]

Overview

Civet is essentially a tasteful superset of TypeScript.

Implementations of New and Proposed ES Features

See thedocumentation for examples of theseand other features.

  • Pattern matching (based onTC39 proposal)
    • switch can match patterns like[{type: "text", name}, ...rest]
  • Pipe operator (based onF# pipes,Hack pipes and theTC39 proposal)
    • data |> Object.keys |> console.log equivalent toconsole.log(Object.keys(data))
    • Use single-argument arrow functions or& shorthandto specify how to use left-hand side
    • |> await,|> yield, and|> return (at end)for wrapping left-hand side with that operation
  • Short function block syntax likeRuby symbol to proc,Crystal,Elm record access
    • Access:x.map &.name orx.map .namex.map(a => a.name)
    • Nested access + slices:x.map &.profile?.name[0...3]x.map(a => a.profile?.name.slice(0, 3))
    • Function call:x.map &.callback a, bx.map($ => $.callback(a, b))
    • Unary operators:x.map !!&x.map($ => !!$)
    • Binary operators:x.map &+1x.map($ => $+1)
  • Object literal shorthand
    • {foo()}{foo: foo()},{props.foo}{foo: props.foo}
    • {`${x}${y}`: z}{[`${x}${y}`]: z}
    • data.{x,y} ordata{x,y}{x: data.x, y: data.y}
    • Flagging shorthand based onfrom LiveScript:{+debug, -live, !verbose}{debug: true, live: false, verbose: false}
  • Custom infix operators from any two-argument function
  • do expressions,if expressions,for expressions

Convenience for ES6+ Features

  • Const assignment shorthand:a := bconst a = b,{a, b} := cconst {a, b} = c
  • Let assignment shorthand:a .= blet a = b
  • Typed versions of above:a: number .= 5let a: number = 5(but note thata: number = 5 is the object literal{a: (number = 5)}).
  • @#idthis.#id shorthand for private identifiers
  • import shorthand:x from ./ximport x from "./x"
  • Dynamicimport shorthand:import './x' not at top level(e.g.await import './x' or inside a function) →import('./x')
  • Optional import rename syntax that corresponds to destructuring renameimport {x: y} from "./z"import {x as y} from "./z". You can stilluseas to be compatible with existing ES imports.
  • export shorthand:export x, yexport {x, y}
  • Triple backtick Template Strings remove leading indentation for clarity
  • Class constructor shorthand@( ... )
  • ClassStaticBlock@ { ... }
  • < asextends shorthand
  • /// Block RegExplike Python re.X

JSX Enhancements

Inspired bysolid-dsl discussionsandjsx spec issues

  • Indentation: instead of explicitly closing<tag>s or<>s,you can indent the children and Civet will close your tags for you
  • Multiple adjacent elements and/or fragments get automaticallycombined into a fragment.
  • Arrow function children do not need to be wrapped in braces(assuming they are not preceded by text); this is unambiguous because> isn't valid JSX text. For example,<For> (item) => ...(where function body can be indented).
  • #foo shorthand forid="foo";also#"foo bar",#`foo ${bar}`,#{expr}
  • .foo shorthand forclass="foo" (but must be at least one space aftertag name); also.foo.bar,."foo bar",.`foo ${bar}`,.{expr}
    • "civet react" flag usesclassName instead ofclass
  • +foo shorthand forfoo={true},-foo/!foo shorthand forfoo={false}
  • Any braced object literal can be used as an attribute:{foo}foo={foo},{foo: bar}foo={bar},{...foo} remains as is; methods and getters/setters work too.
  • Attribute...foo shorthand for{...foo}
  • Attribute values without whitespace or suitably wrapped(parenthesized expressions, strings and template strings,regular expressions, array literals, braced object literals)do not need braces:foo=barfoo={bar},count=count()count={count()},sum=x+1sum={x+1},list=[1, 2, 3]list={[1, 2, 3]}
  • Attributes can use computed property names:[expr]={value}{...{[expr]: value}}
  • "civet solid" flag adds correct types for JSX elements and fragments.Use"civet solid client" (default) for client-only code,"civet solid server" for server-only code (SSR only), or"civet solid client server" for isomorphic code that runs onclient and server (SSR + hydration).
  • XML comments:<!-- ... -->{/* ... */}

TypeScript Enhancements

Changes from ES6

  • Implicit returns, even for multi-statement functions(avoid by specifying avoid return type, adding a trailing; orexplicitreturn, or via the directive"civet -implicitReturns")
  • Disallow no parens on single argument arrow function.x => ... must become(x) => ...The reasoning isx -> ... =>x(function() ...) in CoffeeScript and having-> and=>behave more differently than they already do is bad. Passing an anonymous function to anapplication without parens is also convenient.
  • for(i of x) ... defaults to const declaration →for(const i of x) ...
  • Disallow comma operator in conditionals and many other places.if x, y is not allowed. Butfor i = 0, l = a.length; i < l; i++, i *= 2 is allowed.
  • Comma operator incase/when instead becomes multiple conditions.
  • Numbers can't end with a dot (otherwise would be ambiguous with CoffeeScript slicesy[0..x]). This also implies that you can't access propertiesof numbers with1..toString() use1.toString() instead. When exponent follows a dot it is treated as a property access since an exponentcould be a valid property1.e101..e10. The workaround is to add a trailing zero1.0e10 or remove the dot before the exponent1e10.
  • Additional reserved wordsand,or,loop,until,unless
  • Experimental decorator syntax is@@ instead of@ because@ is premium real estate and@idthis.id, and@ is also static fields/methods, etc.
    @@classDecoratorclass X  @@methodDecorator  method() {}
  • when inside switch automatically breaks and adds block scope.
  • else inside switch adds block scope.
  • No whitespace between unary operators and operands. Mandatory whitespace between condition and ternary? ex.x ? a : b sincex? is the unary existential operator.
  • Labels written:label (except for special case$: for Svelte)

Scripting Improvements

  • Shebang line is kept unmodified in output
    #!./node_modules/.bin/ts-nodeconsole.log "hi"

Comparison to CoffeeScript

Take a look at thisdetailed Civet // CoffeeScript comparision

Directives

Civet is not just one language; it can be configured in a variety of waysvia directives to add or remove language features, or improve behaviorin certain environments.Seeconfig documentation.

Using Civet in your Node.js Environment

You have now been convinced that Civet is right for your current/next project. Here is howto set up your environment to get productive right away and have a Good Time℠.

Testing

Code coverage withc8 "just works" thanks to their source mapintegration and Civet's source maps.

c8 + Mocha

package.json

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

If you don't care for code coverage you can skip c8 (but it is so easy why not keep it?).

You can also add.js and.ts extensions if you want to mix and match! Even.coffee will work if you requirecoffeescript/register or add a loader for it.

Execute the tests

yarntest

Step 4: Enjoy!

Developing

Use the alpha version ofCivet Language Server

The language server provides syntax highlighting, completions, hover documentation, symbols outline, red squigglies, and go to definition.


Q? Why can't I just use the built-in VSCode TypeScript LSP?

A: VSCode's built in TypeScript LSP can't resolve non.ts/.js, not even with plugins. Maybe one day they'll allow forplugins that let you adjust the resolver and insert a transpilation step but until then a separate language server is necessary.


Q? Sometimes the file outline disappears and the red squigglies are all in the wrong place and maybe a notification pops upabout some kind of LSP error.

A: I'm sorry that happened to you but the Civet Language Server is still alpha and improving rapidly. Please let me knowexactly what happened and I'll try to do better next time.

It may happen when there is a syntax error in your Civet file. You can check and see if it compiles using the CLI tool in the meantime.

Please do submit bug reports / feature requests.

Building

I strongly recommend usingesbuild for building / packaging your Civet project.

importesbuildfrom'esbuild'importcivetPluginfrom'@danielx/civet/esbuild-plugin'esbuild.build({  ...,plugins:[civetPlugin]}).catch(()=>process.exit(1))

It's super fast and works great!

Code Coverage

Coverage Status

Sponsorship

If you are so inclined, you can sponsor Civet onOpen Collective.

About

A TypeScript superset that favors more types and less typing

Topics

Resources

License

Stars

Watchers

Forks

Contributors24


[8]ページ先頭

©2009-2025 Movatter.jp