introduction
URL 导入是一个实验性特性,能够直接从外部服务器导入模块(而不是从本地磁盘) ..
警告,这个特性是实验性的,仅仅使用域名(你信任去下载和在你机器上执行脚本的域名),请慎重体验,并保持小心(直到这个特性变得稳定) ..
为了引入,配置URL 前缀
module.exports = {experimental: {urlImports: ['https://example.com/modules/'],},}
然后你能够直接从URLS中导入模块 ..
import { a, b, c } from 'https://example.com/modules/some/module.js'
URL 导入能够在使用在任何包导入的地方使用 ..
安全模型
这个特性是设计来使用最高优先级的安全,为了开始,我们需要增加一个实验性标志强制显式允许这些域名(你从这些地方访问导入的URL),在未来可以通过限制URL 导入执行在浏览器的沙箱中(通过Edge 运行时) ..
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进行响应,这些资源将包含一个no-cache条目到lockfile中,将总是从网络中抓取(在每一次构建之中) ..
例子
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://github.com/vercel/next.js/raw/canary/test/integration/production/public/vercel.png'export default () => (<div><Image src={logo} placeholder="blur" /></div>)
在CSS中的URLs
.className {background: url('https://github.com/vercel/next.js/raw/canary/test/integration/production/public/vercel.png');}
静态资源导入
import Image from 'next/image'const logo = new URL('https://github.com/vercel/next.js/raw/canary/test/integration/production/public/vercel.png',import.meta.url)export default () => <div>{logo.pathname}</div>
