urlImports
配置 Next.js 以允许从外部 URL 导入模块。
此功能目前处于实验阶段,可能会发生变更,不建议在生产环境中使用。欢迎试用并在 GitHub 上分享你的反馈。
URL 导入是一项实验性功能,允许你直接从外部服务器(而非本地磁盘)导入模块。
警告:
仅使用你信任的域名来下载并在你的机器上执行代码。在该功能被标记为稳定之前,请自行斟酌并保持谨慎。
要启用此功能,请在 next.config.js 中添加允许的 URL 前缀:
next.config.jsjs
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 在浏览器沙箱中执行。
锁文件
使用 URL 导入时,Next.js 会创建一个 next.lock 目录,其中包含锁文件和已获取的资源。
该目录必须提交到 Git,不能被 .gitignore 忽略。
- 运行
next dev时,Next.js 会下载所有新发现的 URL 导入并将其添加到你的锁文件中。 - 运行
next build时,Next.js 将仅使用锁文件来构建生产环境的应用。
通常不需要任何网络请求,而过时的锁文件会导致构建失败。
一个例外是响应 Cache-Control: no-cache 的资源。
这些资源会在锁文件中有一个 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"