Next.js 在启动应用程序时运行函数/脚本 [英] Next.js run function/script when starting app

查看:39
本文介绍了Next.js 在启动应用程序时运行函数/脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个(服务器端)函数,我想在第一次启动我的 next.js 服务器时运行.通常我会在我的 package.json 脚本定义中做这样的事情: node ./path/to/script.js &&下一个开始.但是有问题的脚本从webpacked"代码中导入了几个资源,所以这并不容易.(我知道可以使用 --experimental-modules 在 node.js 中打开 es6 支持,但这会带来自己的问题,我宁愿不去那个兔子洞)

I have a (server-side) function I'd like to run when first starting my next.js server. Ordinarily I'd do something like this in my package.json script definition: node ./path/to/script.js && next start. But the script in question imports several resources from "webpacked" code, so that's not so easy. (I know it's possible to turn on es6 support in node.js with --experimental-modules, but this brings its own problems and I'd rather not go down that rabbit hole)

到目前为止,我最好的解决方案是创建一个 api 端点来运行这些脚本,然后在启动后手动点击该端点.但是这样做似乎是一种黑客行为,如果有人发现它,这个端点可能会被用于某种 DoS 攻击.

The best solution I have so far is to create an api endpoint to run these scripts and then either manually hit that endpoint after starting. But it seems like such a hack to do this, and it's possible that this endpoint could be used in some sort of DoS attack if someone found it.

是否有更好的解决方案,只允许注册一个函数/回调以在应用程序启动时运行?我想一个可能的地方是 next.config.js 但我在可能的设置列表中看不到任何可能的内容.

Is there a better solution, something that just allows one to register a function/callback to be run when the app is starting? I figured a likely place would be the next.config.js but I don't see anything likely in the list of possible settings.

推荐答案

我猜你可以使用 next.config 文件中的 webpack 配置来注册一个新插件并在构建完成后运行它.

I guess you could use the webpack configuration on the next.config file to register a new plugin and run it after the build is done.

module.exports = {
    webpack: (config, options) => {
        config.plugins.push(
            {
                apply: (compiler) => {
                    compiler.hooks.afterEmit.tap('AfterEmitPlugin', (compilation) => {
                        console.log(".. Run after build")
                    });
                }
            }    
        )
        return config
    },
}

这篇关于Next.js 在启动应用程序时运行函数/脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆