惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

K
Kaspersky official blog
小众软件
小众软件
Engineering at Meta
Engineering at Meta
博客园 - 三生石上(FineUI控件)
WordPress大学
WordPress大学
G
Google Developers Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
V
V2EX
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Google DeepMind News
Google DeepMind News
Security Archives - TechRepublic
Security Archives - TechRepublic
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
C
Check Point Blog
aimingoo的专栏
aimingoo的专栏
罗磊的独立博客
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
MongoDB | Blog
MongoDB | Blog
L
LINUX DO - 热门话题
酷 壳 – CoolShell
酷 壳 – CoolShell
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
H
Help Net Security
Martin Fowler
Martin Fowler
G
GRAHAM CLULEY
Simon Willison's Weblog
Simon Willison's Weblog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - Franky
V
Vulnerabilities – Threatpost
云风的 BLOG
云风的 BLOG
博客园_首页
C
Cybersecurity and Infrastructure Security Agency CISA
量子位
Stack Overflow Blog
Stack Overflow Blog
Recent Announcements
Recent Announcements
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
I
Intezer
Scott Helme
Scott Helme
A
About on SuperTechFans
博客园 - 司徒正美
Hacker News: Ask HN
Hacker News: Ask HN
The GitHub Blog
The GitHub Blog
Forbes - Security
Forbes - Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
博客园 - 聂微东
人人都是产品经理
人人都是产品经理
The Cloudflare Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Spread Privacy
Spread Privacy
T
Tailwind CSS Blog
S
Security Affairs
宝玉的分享
宝玉的分享

oida.dev | TypeScript, Rust

TypeScript's `erasableSyntaxOnly` Flag Unsafe for work Tokio: Macros Tokio: Channels Tokio: Getting Started Network Applications on the Tokio Stack Remake, Remodel, Reduce. The `never` type and error handling in TypeScript 5 Inconvenient Truths about TypeScript Refactoring in Rust: Introducing Traits Refactoring in Rust: Abstraction with the Newtype Pattern Announcing the TypeScript Cookbook TypeScript: Iterating over objects The road to universal JavaScript 10 years of oida.dev Rust: Tiny little traits The TypeScript converging point How not to learn TypeScript Getting started with Rust Introducing Slides and Coverage TypeScript: The humble function overload TypeScript + React: Children types are broken TypeScript: In defense of any Rust: Enums to wrap multiple errors Dissecting Deno Error handling in Rust TypeScript: Unexpected intersections Upgrading Node.js dependencies after a yarn audit TypeScript: Array.includes on narrow types TypeScript + React: Typing Generic forwardRefs shared, util, core: Schroedinger's module names Learning Rust and Go TypeScript: Narrow types in catch clauses TypeScript: Low maintenance types Tidy TypeScript: Name your generics Tidy TypeScript: Avoid traditional OOP patterns Tidy TypeScript: Prefer type aliases over interfaces Tidy TypeScript: Prefer union types over enums My new book: TypeScript in 50 Lessons Go Preact! ❤️ this in JavaScript and TypeScript TypeScript and ECMAScript Modules TypeScript + React: Why I don't use React.FC TypeScript + React: Component patterns TypeScript: Augmenting global and lib.dom.d.ts TypeScript: Union to intersection type 11ty: Generate Twitter cards automatically Are large node module dependencies an issue? TypeScript: Variadic Tuple Types Preview TypeScript: Improving Object.keys Remake, Remodel. Part 4. TypeScript + React: Typing custom hooks with tuple types TypeScript: Assertion signatures and Object.defineProperty TypeScript: Check for object properties and narrow down type Boolean in JavaScript and TypeScript void in JavaScript and TypeScript Symbols in JavaScript and TypeScript Why I use TypeScript TypeScript + React: Extending JSX Elements TypeScript: Validate mapped types and const context TypeScript: Match the exact object shape TypeScript: The constructor interface pattern Streaming your Meetup - Part 4: Directing and Streaming with OBS Streaming your Meetup - Part 3: Speaker audio Streaming your Meetup - Part 2: Speaker video Streaming your Meetup - Part 1: Basics and Projector TypeScript and React Guide: Added a new styles chapter TypeScript and React Guide: Added a new render props chapter TypeScript and React: Styles and CSS TypeScript and React TypeScript and React Guide: Added a new prop types chapter TypeScript without TypeScript -- JSDoc superpowers TypeScript: Mapped types for type maps JAMStack vs serverless web apps The Unsung Benefits of JAMStack Sites TypeScript: Ambient modules for Webpack loaders My most favourite talks in 2018 TypeScript and React Guide: Added a new context chapter TypeScript: Built-in generic types TypeScript: Type predicates JSX is syntactic sugar TypeScript and React Guide: Added a new hooks chapter Getting your CfP application right FAQ on our Angular Connect Talk: Automating UI development TypeScript and Substitutability Debugging Node.js apps in TypeScript with Visual Studio Code From Medium: Deconfusing Pre- and Post-processing From Medium: PostCSS misconceptions Saving and scraping a website with Puppeteer Cutting the mustard - 2018 edition Wordpress as CMS for your JAMStack sites My most favourite podcast episodes in 2017 My most favourite talks in 2017 My most favourite books in 2017 The Best Request Is No Request, Revisited Not so hidden figures - Organizing ScriptConf My podcast journey to ScriptCast Grid layout, grid layout everywhere! #scriptconf and #devone Object streams in Node.js
Vite with Preact and TypeScript
2020-07-06 · via oida.dev | TypeScript, Rust

Update: Please note that this article already has some age and Vite has seen significant updates. Also, the Preact team has created their own preset for Vite which you can find here. Be sure to check that out!

Vite is a new web development build tool by Evan You, the creator of Vue.js. It’s in early beta at the time of this writing and was mainly created for Vue 3, but it’s also able to build React and Preact and has TypeScript support out of the box.

Vite’s biggest difference to other tools is that for development, it relies on the basic loading capabilities of ECMAScript modules. This means that your import statements translate are executed natively by the browser. Vite’s task is to serve your files. Nothing more. Well, a little bit more.

If you have a file that needs transpilation, Vite transpiles them to regular JS for you so the browser knows what to do. This means that

  • JSX, TSX, TS files are transpiled to JavaScript
  • CSS you import in your JavaScript files is transpiled to JavaScript that injects style tags
  • VUE files are also split up and transpiled to whatever they need to be

And you can extend Vite with custom transpilers, like Sass or other CSS preprocessors.

And since there is no bundling work to be done, or excessive dependency trees to be maintained, serving, translating, and hot module replacement is insanely vite … eh … fast!

If you do a production build, Rollup runs under the hood to do proper tree shaking and creating the smallest possible chunks for your deployment.

Vite really feels like it could be the build tool of all build tools. I’m very impressed! There are also some templates for Vue 3, React and Preact available. But at the time of writing, Preact didn’t have any templates with TypeScript support. So I added my own, and this is what I did.

Step 1. Create a new Preact project with Vite #

As mentioned, there is a Preact template for Vite that we are going to use as a base. It already has most of the things wired up, we only need to add TypeScript support.

$ npm init vite-app my-preact-project --template preact

npm init vite-app is a shortcut for npx create-vite-app. It also works with create-react-app or create-next-app, and whatever create- tool there is out there.

Also, we install TypeScript, at least in version 4.0.

$ npm install typescript

Try npm install typescript@beta if TypeScript isn’t at 4.0, yet. This is the first step. Now we set up the configuration.

Step 2. Setting up TypeScript #

There is no TypeScript project without a good TypeScript configuration. Create a tsconfig.json in your root folder and add the following:

{
"compilerOptions": {
"target": "esnext",
"lib": ["DOM", "DOM.Iterable", "esnext"],
"allowJs": false,
"skipLibCheck": false,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve",
"jsxFactory": "h",
"jsxFragmentFactory": "Fragment"
},
"include": ["src"]
}

There’s lots of settings in there, but the most important for our case are the last three lines in compilerOptions:

"jsx": "preserve",
"jsxFactory": "h",
"jsxFragmentFactory": "Fragment"

We set

  • jsx to preserve, which means that TypeScript doesn’t compile JSX. This is done by Vite anyway
  • jsxFactory is h. This is Preact’s virtual DOM implementation. All JSX elements are transpiled to h function calls. See my article on JSX is syntactic sugar if you want to know what’s happening here under the hood.
  • jsxFragmentFactory to Fragment. This is Preact’s fragment component. Fragments are nice because they don’t require you to add wrapping divs. Clean markup when rendered! This setting is new in TypeScript 4, and allows TypeScript to know that you mean Fragment when doing empty <>...</> tags.

Those settings are mostly for the editor experience, so you get proper typings when editing, and all the auto-completion that you love from TypeScript.

Compilation is done by Vite, though. So we also have to adapt vite.config.js a little bit. Right now, vite.config.js looks something like this:

const config = {
jsx: 'preact',
plugins: [preactRefresh()]
}

This JSX preset from Vite injects h globally. This is ok for most JavaScript projects, but TypeScript loses some information on JSX and what your JSX factory function does. That’s why Vite allows us to override the preset with custom JSX info:

const config = {
jsx: {
factory: 'h',
fragment: 'Fragment'
},
plugins: [preactRefresh()]
}

This mirrors what we have in tsconfig.json, cool!

Step 3. Adapting files #

We’re close! The last thing we need to do is adapting files.

  1. Rename all .jsx files to .tsx.
  2. Open index.html and refer to main.tsx instead of main.jsx.

Next, let your tsx files know which factory and fragment factory you are using. Since we are not injecting globally anymore, we need to import them in each file.

import { Fragment, h } from 'preact'

Since we have TypeScript now up and running, our editor already gives us a sweet error message that we use document.getElementById('app') with way too much confidence. This might be null, after all!

Let’s be sure that this element exists:

const el = document.getElementById('app')
if(el) {
render(<App />, el)
}

And that’s it! You can see a rough and unpolished demo setup on GitHub. Let me know what you think!

Further reading #

  • Please also check out Snowpack by Fred K. Schott. A very similar approach and a very detailled explanation on some ground concepts behind O(1) build tooling.

Related Articles