urlImports
experimental
配置 Next.js 以允许从外部 URL 导入模块。
URL 导入是一项实验性功能,可让你直接从外部服务器(而不是从本地磁盘)导入模块。
警告:仅使用你信任的域名在你的机器上下载并执行代码。请谨慎行事,在该功能被标记为稳定之前请保持警惕。
要选择加入,请在 next.config.js 中添加允许的 URL 前缀:
next.config.js
module.exports = {
experimental: {
urlImports: ['https://example.com/assets/', 'https://cdn.skypack.dev'],
},
}然后,你可以直接从 URL 导入模块:
js
import { a, b, c } from 'https://example.com/assets/some/module.js'URL 导入可用于任何可以使用普通包导入的地方。
安全模型#
此功能的设计以安全为首要任务。首先,我们添加了一个实验性标志,强制你明确允许接受 URL 导入的域名。我们正在努力更进一步,通过使用 Edge Runtime 将 URL 导入限制在浏览器沙箱中执行。
锁文件#
使用 URL 导入时,Next.js 将创建一个 next.lock 目录,其中包含锁文件和获取的资源。 此目录必须提交到 Git,而不要被 .gitignore 忽略。
- 运行
next dev时,Next.js 将下载所有新发现的 URL 导入并添加到你的锁文件中。 - 运行
next build时,Next.js 将仅使用锁文件来为生产环境构建应用。
通常不需要网络请求,任何过时的锁文件都会导致构建失败。 一个例外是以 Cache-Control: no-cache 响应的资源。 这些资源将在锁文件中有一个 no-cache 条目,并且每次构建时都会从网络获取。
示例#
Skypack#
js
import confetti from 'https://cdn.skypack.dev/canvas-confetti'
import { useEffect } from 'react'
export default () => {
useEffect(() => {
confetti()
})
return <p>Hello</p>
}静态图片导入#
js
import Image from 'next/image'
import logo from 'https://example.com/assets/logo.png'
export default () => (
<div>
<Image src={logo} placeholder="blur" />
</div>
)CSS 中的 URL#
css
.className {
background: url('https://example.com/assets/hero.jpg');
}资源导入#
js
const logo = new URL('https://example.com/assets/file.txt', import.meta.url)
console.log(logo.pathname)
// 输出 "/_next/static/media/file.a9727b5d.txt"