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

推荐订阅源

C
Check Point Blog
AI
AI
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
U
Unit 42
Vercel News
Vercel News
Stack Overflow Blog
Stack Overflow Blog
P
Proofpoint News Feed
Microsoft Security Blog
Microsoft Security Blog
The GitHub Blog
The GitHub Blog
WordPress大学
WordPress大学
Martin Fowler
Martin Fowler
博客园 - 【当耐特】
B
Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
F
Full Disclosure
Google DeepMind News
Google DeepMind News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
H
Help Net Security
Recorded Future
Recorded Future
N
News and Events Feed by Topic
雷峰网
雷峰网
V
Vulnerabilities – Threatpost
Schneier on Security
Schneier on Security
aimingoo的专栏
aimingoo的专栏
S
Schneier on Security
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
O
OpenAI News
Project Zero
Project Zero
罗磊的独立博客
G
GRAHAM CLULEY
腾讯CDC
P
Privacy International News Feed
V
V2EX
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Hugging Face - Blog
Hugging Face - Blog
爱范儿
爱范儿
H
Heimdal Security Blog
L
LINUX DO - 热门话题
Forbes - Security
Forbes - Security
美团技术团队
MongoDB | Blog
MongoDB | Blog
Security Latest
Security Latest
M
MIT News - Artificial intelligence
T
Tor Project blog
Cisco Talos Blog
Cisco Talos Blog
宝玉的分享
宝玉的分享
T
Threat Research - Cisco Blogs
TaoSecurity Blog
TaoSecurity Blog

Kent C. Dodds Blog

Implementing Hybrid Semantic + Lexical Search Simplifying Containers with Cloudflare Sandboxes Migrating to Workspaces and Nx Offloading FFmpeg with Cloudflare Building Semantic Search on my Content Helping YOU ask ME questions with AI How I used Cursor to Migrate Frameworks The Dow's Start on the Covenant Path 2025 in Review The next chapter: EpicAI.pro AI is taking your job How I increased my visibility Launching Epic Web 2023 in Review Stop Being a Junior RSC with Dan Abramov and Joe Savona Live Stream Fixing a Memory Leak in a Production Node.js App 2022 in Review My Car Accident I Migrated from a Postgres Cluster to Distributed SQLite with LiteFS I'm building EpicWeb.dev A review of my time at Remix Remix: The Yang to React's Yin How I help you build better websites Why I Love Remix The State Initializer Pattern How to React ⚛️ Get a catch block error message with TypeScript Building an awesome image loading experience How Remix makes CSS clashes predictable Introducing the new kentcdodds.com How I built a modern website in 2021 How to use React Context effectively Static vs Unit vs Integration vs E2E Testing for Frontend Apps The Testing Trophy and Testing Classifications Array reduce vs chaining vs for loop Don't Solve Problems, Eliminate Them Super Simple Start to Remix Super Simple Start to ESModules in Node.js JavaScript Pass By Value Function Parameters How to write a Constrained Identity Function (CIF) in TypeScript How to optimize your context value How to write a React Component in TypeScript TypeScript Function Syntaxes Listify a JavaScript Array Build vs Buy: Component Libraries edition Using fetch with TypeScript Wrapping React.useState with TypeScript Define function overload types with TypeScript 2020 in Review Business and Engineering alignment Hi, thanks for reaching out to me 👋 useEffect vs useLayoutEffect Super simple start to Firebase functions Super simple start to Netlify functions Super Simple Start to css variables Favor Progress Over Pride in Open Source Testing Implementation Details How getting into Open Source has been awesome for me useState lazy initialization and function updates Use ternaries rather than && in JSX Application State Management with React Use react-error-boundary to handle errors in React JavaScript to Know for React How I structure Express apps What open source project should I contribute to? When I follow TDD AHA Programming 💡 How I Record Educational Videos Should I write a test or fix a bug? Stop mocking fetch Intentional Career Building Improve test error messages of your abstractions Tracing user interactions with React Eliminate an entire category of bugs with a few simple tools Common mistakes with React Testing Library Super Simple Start to React Stop using client-side route redirects The State Reducer Pattern with React Hooks Function forms Replace axios with a simple custom fetch wrapper How to test custom React hooks React Production Performance Monitoring Should I useState or useReducer? Stop using isLoading booleans Make Your Test Fail Make your own DevTools An Argument for Automation Fix the "not wrapped in act(...)" warning Implementing a simple state machine library in JavaScript 2010s Decade in Review Why users care about how you write code Why I avoid nesting closures Don't call a React function component Why your team needs TestingJavaScript.com Inversion of Control Understanding React's key prop How to Enable React Concurrent Mode How to add testing to an existing project Profile a React App for Performance
Super Simple Start to ESModules in the Browser
2020-01-22 · via Kent C. Dodds Blog

Watch "Use JavaScript Modules in the browser" on egghead.io

I've been writing JavaScript since before JavaScript had modules. When the EcmaScript specification added support for modules I was thrilled, but I was disappointed to learn that it would be a while before this feature was actually implemented and supported.

Well, it's been a while and now all major browsers support ES Modules. So I'd like to show you the super simple start to ES Modules!

Note: You might be interested in my companion post Super Simple Start to ESModules in Node.js

First, we need a JavaScript file that we want to load into our site:

// append-div.js
function appendDiv(message) {
	const div = document.createElement('div')
	div.textContent = message
	document.body.appendChild(div)
}

export { appendDiv }

Next, let's make an HTML file to load that file:

<script type="module">
	import { appendDiv } from './append-div.js'
	appendDiv('Hello from inline script')
</script>

Notice the type="module" attribute there. That's all we need to do to inform the browser that the JavaScript code is a "module" rather than a "script". There are several differences in how the runtime environment handles the JavaScript file based on whether it's a script or a module, but suffice-it to say that one of those differences is when it's a "module" you're allowed to use modules!

Ok, so in our inline script above, we're importing the appendDiv function from the append-div.js file. Unfortunately, to load the module, we can't just open the HTML file in our browser. We have to be using a local server and open the file from that. If you have node.js installed, then you can open your terminal to the directory where you have these files and run this to get a server going:

npx serve

That will output information for where the server is being run and you can open it up (I think the default location is localhost:5000). With that, "Hello from inline script" should appear on the screen. Tada! We've loaded a real EcmaScript Module! Hooray 🎉

Normally we don't write our JavaScript in an inline script in our HTML file, so let's load a module from a file:

// script-src.js
import { appendDiv } from './append-div.js'

appendDiv('Hello from external script')

To load that up, we just add another script tag to our HTML:

<script type="module">
	import { appendDiv } from './append-div.js'
	appendDiv('Hello from inline script')
</script>
<script type="module" src="./script-src.js"></script>

And now if we pull that up on our server, we'll also have "Hello from external script" appear on the screen.

One thing that's important to note here is the inclusion of the .js in our import statement. We may be spoiled by NodeJS and Babel, but in the modules specification we really do have to provide the extension.

One last thing I want to show is that dynamic imports work well too. So if we add another file:

// async-script.js
import { appendDiv } from './append-div.js'

function go() {
	appendDiv('Hello from async script')
}

export { go }

Then we can load that using a dynamic import statement:

// script-src.js
import { appendDiv } from './append-div.js'

appendDiv('Hello from external script')

import('./async-script.js').then(
	(moduleExports) => {
		moduleExports.go()
	},
	(error) => {
		console.error('there was an error loading the script')
		throw error
	},
)

The dynamic import likewise also must point directly to a JavaScript file (with the extension). And to be clear, what's important is not the extension, but the fact that when the browser makes a request to that URL, it receives back a text file which it can execute as JavaScript.

This means that if you happen to have a URL that returns a JavaScript file but doesn't end in .js you are fine omitting that.

import * as d3 from 'https://unpkg.com/d3?module'

The point is, the thing you put in the quotes in your import statements has to point to a JavaScript resource on some server somewhere. Learn more about unpkg.com.

Conclusion

I hope that was helpful/interesting to you! I've put the code for this up on GitHub and you can play around with it yourself. Enjoy!

P.S. A few other resources you might find helpful on this topic: