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 导入的域。我们正在努力通过使用 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
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"这有帮助吗?