[英]Next.js API include a file to all api endpoints
Is it possible (and how) to add some kind of "bootstrap" file (file with side-effects) as a very first file to be included in all APIs in Next.js?是否有可能(以及如何)添加某种“引导程序”文件(具有副作用的文件)作为第一个文件包含在 Next.js 的所有 API 中?
The original use-case is that I've winston logger in a file which I have to put in all API endpoints, but this is quite poor DX.最初的用例是我将 winston logger 放在一个文件中,我必须将其放入所有 API 端点,但这是非常糟糕的 DX。 I just want to say "hey, put this file before all endpoints, so I know (in this case logger) everything is setup".
我只想说“嘿,把这个文件放在所有端点之前,所以我知道(在本例中是记录器)一切都已设置”。
Thanks谢谢
So, I've found the solution in a custom webpack configuration:因此,我在自定义 webpack 配置中找到了解决方案:
import withPlugins from 'next-compose-plugins';
import { patchWebpackConfig } from 'next-global-css';
import images from 'next-images';
import withTM from 'next-transpile-modules';
import { merge } from 'webpack-merge';
export default withPlugins([
images,
withTM([]),
], {
swcMinify: true,
images: {
formats: ['image/avif', 'image/webp']
},
productionBrowserSourceMaps: false,
// experimental: {
// outputStandalone: true,
// },
webpack: (config, {
webpack,
buildId,
isServer,
...options
}) => {
config.plugins.push(
new webpack.DefinePlugin({
'process.env.BUILD_ID': JSON.stringify(buildId),
}),
);
if (isServer) {
return merge(config, {
entry() {
return config.entry().then(entry => {
// this is the interesting part: prefix entry with a bootstrap file, in my case logger side-effect file
Object.keys(entry).map(key => {
entry[key] = {import: ['./src/service/bootstrap.ts', ...entry[key]]};
});
return entry;
});
}
});
}
return patchWebpackConfig(config, options);
},
reactStrictMode: true,
staticPageGenerationTimeout: 15,
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.