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

时间:2020-09-27 19:06:21

标签: javascript firebase google-cloud-functions svelte sapper

问题

我正在构建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日志:

错误:函数终止。建议的操作:检查日志以了解终止原因。函数无法初始化。

{“ @ type”:“ type.googleapis.com/google.cloud.audit.AuditLog”,“状态”:{“代码”:3,“消息”:“”加载用户代码时功能失败。错误消息:错误:请检查您的功能日志以查看错误原因: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"}

我尝试过的

我尝试过:

  • 在开发人员模式下运行应用程序,效果完美

  • 将应用程序构建为js函数,效果完美

  • 通过firebase serve服务应用程序,效果完美

  • 使用firebase deployfirebase deploy --only functions部署应用程序,但都无效,并抛出指定的错误以上

  • 正在检查代码是否存在错误和配置错误,什么都没发现

我尝试使用本文中的知识来解决此问题,我逐步按照本教程的形式进行操作,但是仍然遇到相同的错误:

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 }

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

1 个答案:

答案 0 :(得分:1)

出了什么问题

问题是,我将firebase用于浏览器,Svelte是编译器,它在Node.js环境中运行,它必须由代码捆绑器捆绑(我使用汇总)。为了能够在节点中运行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,
    }
};