urlImports
此功能目前為實驗性質,可能會有所變動,不建議用於生產環境。請試用並在 GitHub 上分享您的意見回饋。
URL imports 是一項實驗性功能,可讓您直接從外部伺服器(而非本機磁碟)匯入模組。
警告:僅使用您信任的網域來下載並在您的機器上執行。在該功能標記為穩定之前,請謹慎行事並保持警惕。
若要選擇加入,請將允許的 URL 字首新增至 next.config.js
中
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 Imports 可用於任何可以使用一般套件匯入的地方。
安全模型
此功能的設計將安全性視為首要考量。首先,我們新增了一個實驗性標記,強制您明確允許接受 URL imports 的網域。我們正努力透過使用 Edge Runtime 將 URL imports 限制在瀏覽器沙箱中執行,以進一步提升安全性。
Lockfile
使用 URL imports 時,Next.js 將建立一個 next.lock
目錄,其中包含 lockfile 和擷取的資源。此目錄必須提交到 Git,而不是被 .gitignore
忽略。
- 執行
next dev
時,Next.js 將下載所有新發現的 URL Imports 並將其新增至您的 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"
這有幫助嗎?