Firebase 将 Sapper 应用部署为云功能失败

Firebase deployng Sapper app as cloud function failed

问题

我正在构建 Sapper SSR 应用程序,它根据 Firebase 实时数据库所需的数据从 Firebase 存储加载内容。我的应用程序部署在 Firebase 云功能上。但是我上次部署时出现了这个错误,因为上次部署我实现了从实时数据库加载一些数据和其他小功能,所以我不知道是什么导致了这个错误。

部署命令:

/usr/bin/node /usr/local/lib/node_modules/npm/bin/npm-cli.js run deploy:functions --scripts-prepend-node-path=auto

> violette-website@0.0.1 deploy:functions /home/hejtmus/Documents/Websites/Violette/sapper/Violette/functions
> firebase deploy --only functions:ssr


=== Deploying to 'violette-77756'...

i  deploying functions
i  functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i  functions: ensuring required API cloudbuild.googleapis.com is enabled...
✔  functions: required API cloudbuild.googleapis.com is enabled
✔  functions: required API cloudfunctions.googleapis.com is enabled
i  functions: preparing functions directory for uploading...
i  functions: packaged functions (4.41 MB) for uploading
✔  functions: functions folder uploaded successfully
i  functions: current functions in project: ssr(us-central1)
i  functions: uploading functions in project: ssr(us-central1)
i  functions: updating Node.js 12 function ssr(us-central1)...
⚠  functions[ssr(us-central1)]: Deployment error.
Function failed on loading user code. Error message: Error: please examine your function logs to see the error cause: https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs


Functions deploy had errors with the following functions:
        ssr


To try redeploying those functions, run:
    firebase deploy --only "functions:ssr"


To continue deploying other features (such as database), run:
    firebase deploy --except functions

Error: Functions did not deploy properly.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! violette-website@0.0.1 deploy:functions: `firebase deploy --only functions:ssr`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the violette-website@0.0.1 deploy:functions script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/hejtmus/.npm/_logs/2020-09-27T18_34_13_296Z-debug.log

Process finished with exit code 1

Firebase 日志:

Error: function terminated. Recommended action: inspect logs for termination reason. Function cannot be initialized.

{"@type":"type.googleapis.com/google.cloud.audit.AuditLog","status":{"code":3,"message":"Function failed on loading user code. Error message: Error: please examine your function logs to see the error cause: https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs"},"authenticationInfo":{"principalEmail":"filip.holcik.official@gmail.com"},"serviceName":"cloudfunctions.googleapis.com","methodName":"google.cloud.functions.v1.CloudFunctionsService.UpdateFunction","resourceName":"projects/violette-77756/locations/us-central1/functions/ssr"}

我试过的

我试过了:

我试着用这篇文章的知识解决了这个问题,我一步一步地按照这个教程来做,但我仍然得到同样的错误:

https://blog.logrocket.com/build-an-ssr-web-app-with-firebase-functions-hosting-and-svelte-sapper/

我也尝试删除我添加的代码并部署应用程序而不从 firebase 实时数据库加载数据,但它没有帮助。

代码:

index.js(云函数):

const functions = require('firebase-functions');
const { sapperServer } = require('./__sapper__/build/server/server');

exports.ssr = functions.https.onRequest(sapperServer);

server.js:

import sirv from 'sirv';
import express from 'express';
import compression from 'compression';
import * as sapper from '@sapper/server';

const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === 'development';

const sapperServer = express()
    .use(
        compression({ threshold: 0 }),
        sirv(`static`, { dev }),
        sapper.middleware()
    )
if(dev){
    sapperServer.listen(PORT, err => {
        if (err) console.log('error', err);
    });
}

export { sapperServer }

如果需要,我会提供更多信息。

问题是什么

问题是,我将 firebase 用于浏览器,Svelte 是编译器,它在 Node.js 环境中 运行s,它必须由代码捆绑器捆绑(我使用汇总)。为了能够在节点中 运行 firebase,只需在汇总配置中指定 mainFields。

resolve({
    browser: true,
    dedupe: ['svelte'],
    mainFields: ['main']
}),

我只在客户端使用 firebase,所以在我的例子中不需要在服务器中指定 mainFields 参数。

完整汇总配置

import resolve from '@rollup/plugin-node-resolve';
import replace from '@rollup/plugin-replace';
import commonjs from '@rollup/plugin-commonjs';
import svelte from 'rollup-plugin-svelte';
import postcss from 'rollup-plugin-postcss';
import autoPreprocess from "svelte-preprocess";
import pluginJson from "@rollup/plugin-json";
import babel from 'rollup-plugin-babel';
import { terser } from 'rollup-plugin-terser';
import config from 'sapper/config/rollup.js';
import pkg from './package.json';

const mode = process.env.NODE_ENV;
const dev = mode === 'development';
const legacy = !!process.env.SAPPER_LEGACY_BUILD;

const onwarn = (warning, onwarn) => (warning.code === 'CIRCULAR_DEPENDENCY' && /[/\]@sapper[/\]/.test(warning.message)) || onwarn(warning);

const preprocessOptions = {
    postcss: {
        plugins: [
            require('postcss-import'),
            require('postcss-preset-env')({
                stage: 0,
                browsers: 'last 2 versions',
                autoprefixer: { grid: true }
            })
        ]
    }
};

export default {
    client: {
        input: config.client.input(),
        output: config.client.output(),
        plugins: [
            replace({
                'process.browser': true,
                'process.env.NODE_ENV': JSON.stringify(mode)
            }),
            svelte({
                preprocess: autoPreprocess(preprocessOptions),
                dev,
                hydratable: true,
                emitCss: true,
                css: css => {
                    css.write('static/css/bundle.css');
                }
            }),
            postcss({
                extract: "static/css/imported.min.css",
                sourceMap: true,
                minimize: true,
            }),
            resolve({
                browser: true,
                dedupe: ['svelte'],
                mainFields: ['main']
            }),
            commonjs(),
            legacy && babel({
                extensions: ['.js', '.mjs', '.html', '.svelte'],
                runtimeHelpers: true,
                exclude: ['node_modules/@babel/**'],
                presets: [
                    ['@babel/preset-env', {
                        targets: '> 0.25%, not dead'
                    }]
                ],
                plugins: [
                    '@babel/plugin-syntax-dynamic-import',
                    ['@babel/plugin-transform-runtime', {
                        useESModules: true
                    }]
                ]
            }),

            !dev && terser({
                module: true
            })
        ],

        onwarn,
    },

    server: {
        input: config.server.input(),
        output: config.server.output(),
        plugins: [
            replace({
                'process.browser': false,
                'process.env.NODE_ENV': JSON.stringify(mode)
            }),
            svelte({
                preprocess: autoPreprocess(preprocessOptions),
                generate: 'ssr',
                dev,
                css: css => {
                    css.write('static/css/bundle.css');
                }
            }),
            postcss({
                extract: "static/css/imported.min.css",
                sourceMap: true,
                minimize: true,
            }),
            resolve({
                dedupe: ['svelte']
            }),
            commonjs(),
            pluginJson(),
        ],
        external: Object.keys(pkg.dependencies).concat(
            require('module').builtinModules || Object.keys(process.binding('natives'))
        ),

        onwarn,
    },

    serviceworker: {
        input: config.serviceworker.input(),
        output: config.serviceworker.output(),
        plugins: [
            resolve(),
            replace({
                'process.browser': true,
                'process.env.NODE_ENV': JSON.stringify(mode)
            }),
            commonjs(),
            !dev && terser()
        ],

        onwarn,
    }
};