我最近决定迁移到 NextJs,但在这样做时遇到了一些问题。我已经编写了 ExpressJs API,现在我想将其用作自定义 NextJs 服务器,正如文档中所述,但我无法使其工作
这是我的 server.ts 文件(我使用的是 Typescript)
///<reference path="../@types/index.d.ts"/>
import express from "express";
import next from "next";
// Rest of the imports (I removed to make the code shorter here)
import api from "./api";
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
const port = process.env.PORT || 3000;
require("dotenv").config();
app
.prepare()
.then(() => {
const server = express();
// All these following middlewares are imported previously
server.use(logger("dev"));
server.use(cors());
server.use(compression());
server.use(express.json());
server.use(express.urlencoded({ extended: false }));
server.use(cookieParser());
server.use(NoCache);
server.use("/api", auth.userHeader(), API); // My routes
server.get("*", (req, res, next) => handle(req, res)); // NextJs Handle
server.use(ErrorHandler);
server.listen(port, () => {
console.log(`Server Listening to port ${port}`);
});
})
.catch((ex) => {
console.error(ex.stack);
process.exit(1);
});
export default app;
Run Code Online (Sandbox Code Playgroud)
我制作了一个非常简单的应用程序来测试它(只有登录页面的链接)
当我使用我的应用程序运行项目时next
[按预期工作并应用样式][2],但显然 ExpressJs API 没有。但是,当我运行该server.ts
文件时,API 按预期工作(所有端点均正常工作),并且我收到了 next 的compiled successfully
消息,但是 [页面变为空白][3]style
自动给予 next 应用,并且也没有 CSS 加载到应用程序(我在body
标签上添加了一个样式,globals.scss
将其显示设置为block !important
,因此它会覆盖使页面不显示的样式)。
这是我的 _app.tsx 文件
import { AuthProvider } from "../context/auth";
import "../styles/globals.scss";
function MyApp({ Component, pageProps }) {
return (
<AuthProvider>
<Component {...pageProps} />
</AuthProvider>
);
}
export default MyApp;
Run Code Online (Sandbox Code Playgroud)
你可以看到我globals.scss
在顶部导入了右侧
这是我的 _document.tsx 文件
import Document, { Html, Head, Main, NextScript } from "next/document";
class NextDocument extends Document {
render() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default NextDocument;
Run Code Online (Sandbox Code Playgroud)
这是我的 next.config.js 文件
module.exports = {
publicRuntimeConfig: {
// Will be available on both server and client
API_URL: process.env.API_URL,
},
};
Run Code Online (Sandbox Code Playgroud)
我有什么遗漏的吗?我按照文档和观看的一些视频进行操作,但仍然没有任何进展
提前致谢。如果您需要任何其他信息,请告诉我。
经过几次测试后,我意识到当我删除打字稿时,一切都很完美。我仍然不知道如何解决它,我不想失去打字稿的所有好处
我的 tsconfig.json
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "CommonJS",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve"
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "pages/a.js", "pages/b.js", "pages/index.js", "server.js"],
"exclude": ["node_modules"]
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2126 次 |
最近记录: |