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

推荐订阅源

Vercel News
Vercel News
O
OpenAI News
Engineering at Meta
Engineering at Meta
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
月光博客
月光博客
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
WordPress大学
WordPress大学
宝玉的分享
宝玉的分享
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
云风的 BLOG
云风的 BLOG
罗磊的独立博客
S
SegmentFault 最新的问题
The Register - Security
The Register - Security
Hugging Face - Blog
Hugging Face - Blog
D
DataBreaches.Net
U
Unit 42
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
B
Blog
阮一峰的网络日志
阮一峰的网络日志
P
Proofpoint News Feed
雷峰网
雷峰网
V
Visual Studio Blog
小众软件
小众软件
aimingoo的专栏
aimingoo的专栏
N
Netflix TechBlog - Medium
酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Y
Y Combinator Blog
博客园 - 【当耐特】
G
Google Developers Blog
L
LangChain Blog
Stack Overflow Blog
Stack Overflow Blog
I
InfoQ
Martin Fowler
Martin Fowler
F
Fortinet All Blogs
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
The Cloudflare Blog
AI
AI
Google Online Security Blog
Google Online Security Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
博客园 - Franky
Blog — PlanetScale
Blog — PlanetScale
Webroot Blog
Webroot Blog
PCI Perspectives
PCI Perspectives
爱范儿
爱范儿
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org

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 + React: Why I don't use React.FC TypeScript + React: Component patterns TypeScript: Augmenting global and lib.dom.d.ts Vite with Preact and TypeScript 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
TypeScript and ECMAScript Modules
2020-08-14 · via oida.dev | TypeScript, Rust

Working with real, native, ECMAScript modules is becoming a thing. Tools like Vite, ES Dev server, and Snowpack get their fast development experience from leaving module resolution to the browser. Package CDNs like Skypack and UnPKG are providing pre-compiled ES modules which you can use in both Deno and the browser just by referencing a URL.

Combined with proper caching and knowing what HTTP can do, ES modules can become a real alternative to all the heavy bundling and building that we’re used to. If you want to work with ECMAScript modules and TypeScript, there are a few things to consider.

Working with your own modules #

What we want to achieve is to write import and export statements in TypeScript:

// File module.ts
export const obj = {
name: 'Stefan'
}

// File index.ts
import { obj } from './module'

console.log(obj.name)

But preserve the syntax and let the browser handle module resolution. To do this, we need to tell TypeScript to

  1. Compile to an ECMAScript version that understands modules
  2. Use the ECMAScript module syntax for module code generation

Let’s define this in our tsconfig.json:

{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
}
}

I usually use esnext which is always the latest ECMAScript version, but you might want to go to a specific year depending on the rest of the ES features you are using. All options starting from es2015 onwards are compatible.

This already does one important thing: It leaves the syntax intact. A problem occurs once we want to run our code. Usually, we import from TypeScript files without an extension. Specifying a ts extension actually results in a compiler error. Once we compile, the extension is still missing. But the browser needs an extension to actually point to the respective JavaScript file.

The solution: Specify a js extension, even though you are pointing to a ts file when you develop. TypeScript is smart enough to pick that up.

// index.ts

// This still loads types from 'module.ts', but keeps
// the reference intact once we compile.
import { obj } from './module.js'

console.log(obj.name)

The same goes for tsx files. TypeScript knows tsx files get compiled to a js file, so it’s safe to use the js extension once you import.

// Component.tsx
import { h } from 'preact';

export function Hello() {
return <div>
<h1>Hello World</h1>
</div>
}

// index.ts
import { Hello } from './Component.js';

console.log(Hello)

That’s all you need for local!

Working with modules over HTTP #

It gets a lot more interesting when we want to use dependencies that live under a specific URL. Let’s say we want to import Preact directly from Skypack or UnPKG.

import { h } from 'https://cdn.skypack.dev/preact@^10.4.7';

TypeScript immediately throws a TS 2307 error at us: Cannot find module ‘…’ or its corresponding type declarations.(2307). TypeScript’s module resolution works when files are on your disk, not on some server via HTTP. To get the info we need, we have to provide TypeScript with a resolution of our own.

With types #

Let’s say we want to have type information. We can point TypeScript to read the respective type information from our local disk. Either get a good .d.ts file or install the missing dependency via NPM.

$ npm install [email protected]

Or just the types depending on your library:

$ npm install @types/react

Next, do a path alias so TypeScript knows where to pick up types:

{
"compilerOptions": {
...
"paths": {
"https://cdn.skypack.dev/preact@^10.4.7": [
"node_modules/preact/src/index.d.ts"
]
}
}
}

Be sure you find the correct file, otherwise, your typings get all messed up.

Without types #

One of the cool things in TypeScript is that we can decide which types we want to have, and which we don’t want to have. any might seem like an escape hatch, but it can also be an intentional choice to not use types for a part of your application.

Maybe we want to load a module that we don’t really need to understand the interface or have to interact with the API, why bother wiring up types anyway?

TypeScript has an explicit any for imports, and it’s called ts-ignore:

//@ts-ignore
import { h } from 'https://cdn.skypack.dev/preact@^10.4.7';

// h is any

ts-ignore removes the next line from type checking. This also goes for other parts of our application, not just imports. In our case, h comes into existence, but TypeScript doesn’t know the types because we ignored type checking and inferring.

And for some cases, this is totally fine.

Deno #

Everything we heard so far goes for the browser, but there is one other runtime that uses ES imports in TypeScript: Deno. In Deno, ES imports via URLs are a first-class citizen and the preferred way to import dependencies. Since this is so heavily tied to how Deno works, Deno treats imports a bit differently.

  1. Everything you write is TypeScript, so no need to use extensions
  2. Deno throws the same TS 2307 at you once you import it from a URL. But the first time you run your application, Deno fetches the dependency and can do module resolution and type provision from the locally cached dependency.
  3. If you use a CDN like Skypack, it’s possible that types are sent along for regular JS dependencies. See how that works in Fred’s article on Dev.to

Related Articles