Next.js静态导出(SSG)全局CSS加载CORS错误解决方案求助
问题:Next.js静态导出后本地打开HTML无法加载全局CSS(无需服务器)
我使用React、Next.js和styled-components开发项目,已按文档设置好文件结构,希望静态导出的HTML页面能直接从文件资源管理器打开并正常加载全局CSS,确保Next.js的SSG功能正常。注意:不要建议使用服务器,我知道这是简单方案,我需要实现本地直接打开静态文件就能运行。
文件结构
pages/ _app.tsx _document.tsx index.tsx styles/core.css
当前实现
_app.tsx 代码
我在_app.tsx中直接导入全局CSS:
import { AppProps } from 'next/app'; import '../styles/core.css'; function MyApp({ Component, pageProps }: AppProps) { return <Component {...pageProps} /> } export default MyApp;
静态导出后的问题
执行SSG生成页面后,生成的HTML文件包含以下两行:
<link rel="preload" href="/_next/static/css/4da684a704d068a3.css" as="style" crossorigin=""/> <link rel="stylesheet" href="/_next/static/css/4da684a704d068a3.css" crossorigin="" data-n-g=""/>
直接打开index.html时控制台报错:
Access to CSS stylesheet at 'file:///C:/_next/static/css/4da684a704d068a3.css' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome-untrusted, https, edge.
手动将HTML中的link标签修改为相对路径后就能正常工作:
<link rel="stylesheet" href="_next/static/css/4da684a704d068a3.css">
但我找不到自动化解决这个问题的方案,恳请帮助。
相关参考文件
_document.tsx 代码
import Document, { Head, Html, Main, NextScript, DocumentContext, DocumentInitialProps } from 'next/document' import { ServerStyleSheet } from 'styled-components' export default class MyDocument extends Document { render() { return ( <Html lang="en"> <Head /> <body> <Main /> <NextScript /> </body> </Html> ) } static async getInitialProps(ctx: DocumentContext): Promise<DocumentInitialProps> { const sheet = new ServerStyleSheet() const originalRenderPage = ctx.renderPage try { ctx.renderPage = () => originalRenderPage({ enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />), }) const initialProps = await Document.getInitialProps(ctx) return { ...initialProps, styles: ( <> {initialProps.styles} {sheet.getStyleElement()} </> ), } } finally { sheet.seal() } } }
Next.js 配置文件
/** @type {import('next').NextConfig} */ const nextConfig = { reactStrictMode: true, output: 'export', compiler: { styledComponents: true, }, } module.exports = nextConfig
内容的提问来源于stack exchange,提问作者killamocingbird
相关产品推荐
相关产品推荐

