瀏覽器似乎將 JavaScript 檔案讀取為 HTML 並收到“Uncaught SyntaxError: Unexpected token '<'”
<p>類似於這個未回答的問題:瀏覽器似乎將 React JS 檔案讀取為 HTML,而不是 JSX</p>
<p>我有一個使用 Next.js、React 和 Typescript 建置的專案。 </p>
<p>但現在我正在嘗試添加一些 Javascript 文件,例如 <code>testScroll.js</code>:</p>
<pre class="brush:php;toolbar:false;">function init() {
window.scrollTo(0, 1);
window.scrollTo(0, -1);
console.log('scrolling')
}
init()</pre>
<p>我將此腳本保存在 <code>public/js/testScroll.js</code> 上。我嘗試在這個 <code>index.tsx</code> 元件上使用它:</p>
<pre class="brush:php;toolbar:false;">import { type NextPage } 從 "next";
import { Footer, Header, HomePageWrapper } from "~/componentsFromWebflow/homeComponents";
import Script from "next/script";
import Head from "next/head";
const Home: NextPage = () => {
return (
<>
<Head>
<meta charSet="utf-8" />
<title>Ace-it</title>
<meta name="description" content="content" />
<meta content="width=device-width, initial-scale=1" name="viewport" />
<link href="https://fonts.googleapis.com" rel="preconnect" />
<link href="https://fonts.gstatic.com" rel="preconnect" crossOrigin="anonymous" />
<link href="https://uploads-ssl.webflow.com/64296e49c388ed7c157635f0/64296e49c388eda6b076360c_Faivcon 32.svg" rel="shortcut icon" type="image/x-icon" />
<link href="https://uploads-ssl.webflow.com/64296e49c388ed7c157635f0/64296e49c388edc81976360d_Faivcon 256.svg>t /relw>
<link rel="icon" href="/favicon.ico" />
</Head>
<Header />
<HomePageWrapper />
<Footer />
<Script src="./js/scrollTest.js"
type="text/javascript"
strategy="beforeInteractive" />
</>
);
};
export default Home;</pre>
<p>我已經嘗試了 <code>Script</code> 標記的所有可能策略,但沒有任何效果。</p>
<p>問題是<strong>當我第一次加載頁面時,它會拋出以下錯誤</strong>:</p>
<blockquote>
<p>未捕獲的語法錯誤:意外的標記“<”(位於scrollTest.js:1:1)</p>
</blockquote>
<p>當然,如果我檢查資源管理器上的「來源」選項卡,它看起來像這樣:</p>
<p><strong>但在重新加載幾次之後</strong>(通常只有一次),它<strong>開始工作</strong>並顯示正確的代碼:
</p>
<p>另外,我有一個 <code>middleware.ts</code>:</p>
<pre class="brush:php;toolbar:false;">import { getAuth, withClerkMiddleware } from "@clerk/nextjs/server";
import { NextResponse } from "next/server";
import type { NextRequest } from 'next/server'
// Set the paths that don't require the user to be signed in
const publicPaths = ['/', '/api/stripe-webhook*', '/api/clerk-webhook*']
const isPublic = (path: string) => {
return publicPaths.find(x =>
path.match(new RegExp(`^${x}$`.replace('*$', '($|/)')))
)
}
export default withClerkMiddleware((req: NextRequest) => {
if (isPublic(req.nextUrl.pathname)) {
return NextResponse.next()
}
console.log("middleware running");
const { userId } = getAuth(req);
if (!userId) {
console.log('userId is null, undefined or empty');
const indexUrl = new URL('/', req.url)
indexUrl.searchParams.set('redirect_url', req.url)
return NextResponse.redirect(indexUrl)
}
return NextResponse.next();
});
// Stop Middleware running on static files
export const config = { matcher: '/((?!_next/image|_next/static|favicon.ico).*)', };</pre>
<p>似乎如果我從資源管理器中刪除 cookie,就會出現錯誤,但仍然不知道原因以及如何修復它。 </p>
<p>發生了什麼事以及如何解決? </p>