Next.js中间件在TypeScript中未能正常工作 – 我做错了什么?

huangapple go评论56阅读模式
英文:

Next.js middleware not functioning correctly in TypeScript - what am I doing wrong?

问题

我的问题是,按照文档,Next.js的中间件不像我期望的那样工作。

我尝试了这个。这是我能想象到的最简单的中间件。

我期望在导航到 / 时,会出现一个控制台消息。但什么都没有发生。

这里是代码:

Next.js中间件在TypeScript中未能正常工作 – 我做错了什么?

我还删除了 package-lock,并重新安装了所有内容。现在这是我的 package 文件:

{
  "dependencies": {
    "@next/swc-darwin-x64": "13.4.4",
    "eslint-config-next": "13.3.0",
    "next": "13.3.0",
    "react": "18.2.0",
    "react-dom": "18.2.0"
  },
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next list"
  },
  "devDependencies": {
    "@types/node": "18.15.11",
    "@types/react": "18.0.35"
  }
}
英文:

My problem is that following documentation, Next.js's middleware are not working as I ewxpected.

I tried this. The simpletst middleware I can imagine.

I expected navigating throw /, ... a console message will appear. But nothing happened.

Here the code:

Next.js中间件在TypeScript中未能正常工作 – 我做错了什么?

I've also removed package-lock. Reinstalled everything. Now this is my package file:

{
  "dependencies": {
    "@next/swc-darwin-x64": "13.4.4",
    "eslint-config-next": "13.3.0",
    "next": "13.3.0",
    "react": "18.2.0",
    "react-dom": "18.2.0"
  },
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next list"
  },
  "devDependencies": {
    "@types/node": "18.15.11",
    "@types/react": "18.0.35"
  }
}

答案1

得分: 2

NextJS 13+要求middleware文件位于源代码的根级目录,而不是app/或任何其他文件夹中。

因此,你的中间件文件和项目目录应该如下所示:

├── next.config.ts
├── middleware.ts
├── .env,package.json或任何其他项目文件
├── app
├── pages
├── public
├── src

参考链接

英文:

NextJS 13+ requires middleware file to be at the root level of your source instead of app/ or any other folder.

So your middleware file and project dir should look like

├── next.config.ts
├── middleware.ts
├── .env, package.json, or any other project files
├── app
├── pages
├── public
├── src

Reference

huangapple
  • 本文由 发表于 2023年5月28日 17:17:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76350773.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定