urlImports
此功能目前为实验性,可能会发生变化,不建议用于生产环境。请尝试使用并在 GitHub 上分享您的反馈。
URL 导入是一项实验性功能,允许您直接从外部服务器(而不是本地磁盘)导入模块。
警告:仅使用您信任的域名在您的机器上下载和执行。请谨慎行事,并在该功能被标记为稳定之前保持警惕。
要选择启用,请在 next.config.js
中添加允许的 URL 前缀
next.config.js
module.exports = {
experimental: {
urlImports: ['https://example.com/assets/', 'https://cdn.skypack.dev'],
},
}
然后,您可以直接从 URL 导入模块
import { a, b, c } from 'https://example.com/assets/some/module.js'
URL 导入可以在任何可以使用普通包导入的地方使用。
安全模型
此功能的设计以安全性为首要考虑。首先,我们添加了一个实验性标志,强制您显式允许您接受 URL 导入的域名。我们正在努力进一步推进,通过限制 URL 导入在浏览器沙箱中使用 Edge Runtime 执行。
Lockfile
当使用 URL 导入时,Next.js 将创建一个 next.lock
目录,其中包含一个 lockfile 和获取的资源。此目录必须提交到 Git,而不是被 .gitignore
忽略。
- 当运行
next dev
时,Next.js 将下载并将所有新发现的 URL 导入添加到您的 lockfile 中。 - 当运行
next build
时,Next.js 将仅使用 lockfile 来构建用于生产环境的应用程序。
通常,不需要网络请求,任何过时的 lockfile 都会导致构建失败。一个例外是响应 Cache-Control: no-cache
的资源。这些资源将在 lockfile 中有一个 no-cache
条目,并且始终在每次构建时从网络获取。
示例
Skypack
import confetti from 'https://cdn.skypack.dev/canvas-confetti'
import { useEffect } from 'react'
export default () => {
useEffect(() => {
confetti()
})
return <p>Hello</p>
}
静态图像导入
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
.className {
background: url('https://example.com/assets/hero.jpg');
}
资源导入
const logo = new URL('https://example.com/assets/file.txt', import.meta.url)
console.log(logo.pathname)
// prints "/_next/static/media/file.a9727b5d.txt"
这对您有帮助吗?