urlImports

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 导入可用于所有常规包导入的使用场景。

安全模型

此功能的设计以安全性为首要原则。初始阶段,我们通过实验性标志强制要求您显式声明允许导入的域名。我们正进一步将其限制在浏览器沙箱中执行,使用 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)

// 输出 "/_next/static/media/file.a9727b5d.txt"

On this page