I was trying to deploy my react ssr to firebase functions and this error appeared to me, can someone help me?
i functions: Watching "C:\Users\LucasPereira\Documents\Dev\Site\ProIT\frontend\functions" for Cloud Functions...
! C:\Users\LucasPereira\Documents\Dev\Site\ProIT\frontend\functions\src\assets\gif_pro_it.gif:1
GIF89a
SyntaxError: Invalid or unexpected token
at wrapSafe (internal/modules/cjs/loader.js:1167:16)
at Module._compile (internal/modules/cjs/loader.js:1215:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1272:10)
at Module.load (internal/modules/cjs/loader.js:1100:32)
at Function.Module._load (internal/modules/cjs/loader.js:962:14)
at Module.require (internal/modules/cjs/loader.js:1140:19)
at require (internal/modules/cjs/helpers.js:75:18)
at Object.<anonymous> (C:\Users\LucasPereira\Documents\Dev\Site\ProIT\frontend\functions\src\pages\Home\index.js:22:42)
at Module._compile (internal/modules/cjs/loader.js:1251:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1272:10)
! We were unable to load your functions code. (see above)
This is my index.tx(root)
import * as functions from 'firebase-functions';
import React from 'react';
import { renderToString } from 'react-dom/server';
import App from './src/App';
import express from 'express';
import fs from 'fs';
const index = fs.readFileSync(__dirname + '/index.html', 'utf-8');
const app = express();
app.get('**', (req, res)=>{
const html = renderToString(<App />);
const finalHtml = index.replace('<div id="root"></div>', `<div id="root">${html}</div>`);
res.set('Cache-Control', 'public, max-age=600, s-maxage=1200');
res.send(finalHtml);
})
export let ssrapp = functions.https.onRequest(app);
This is my firebase.json
{
"hosting": {
"public": "dist",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"function": "ssrapp",
"destination": "/index.html"
}
]
},
"functions": {
"predeploy": {},
"source": "functions"
}
}
NOTE: I'm using express 4.17.1, and node version 14.
The host is working very well i'm only having problem with functions
EDIT: I change the ".gif" and it continues showing error, so I decided to remove it, only for debug, well, the error continues to another image(another PNG), the error appears to be in images
It looks like you're trying to import a *.gif image somewhere (but not in the provided code); by default, importing GIFs is not supported.
If I'm correct, then you need to setup Webpack (or its alternatives) in order to handle imports of GIF files.
Related
I've tried to build my vue web app using this config, but I got these errors, I've tried this issue but I can't found someone got the same issue as me. How can I deal with this issue, by the way the build succeeded, the issues happened when I tried to run node src/server.jsx? Thanks in advance
$ node src/server.jsx
D:\myPathProject\node_modules\#vue\server-renderer\dist\server-renderer.cjs.js:994
vue.initDirectivesForSSR();
^
TypeError: vue.initDirectivesForSSR is not a function
at Object.<anonymous> (D:\myPathProject\node_modules\#vue\server-renderer\dist\server
-renderer.cjs.js:994:5)
at Module._compile (internal/modules/cjs/loader.js:1072:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
at Module.load (internal/modules/cjs/loader.js:937:32)
at Function.Module._load (internal/modules/cjs/loader.js:778:12)
at Module.require (internal/modules/cjs/loader.js:961:19)
at require (internal/modules/cjs/helpers.js:92:18)
at Object.<anonymous> (D:\myPathProject\node_modules\#vue\server-renderer\index.js:6:
20)
at Module._compile (internal/modules/cjs/loader.js:1072:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
this is my vue.config.js file
/* eslint-disable #typescript-eslint/no-var-requires */
const { WebpackManifestPlugin } = require("webpack-manifest-plugin")
const nodeExternals = require("webpack-node-externals")
exports.chainWebpack = (webpackConfig) => {
if (!process.env.VUE_APP_SSR) return
webpackConfig
.entry("app")
.clear()
.add("./src/main.server.ts")
webpackConfig.target("node")
webpackConfig.output.libraryTarget("commonjs2")
webpackConfig
.plugin("manifest")
.use(new WebpackManifestPlugin({ fileName: "ssr-manifest.json" }))
webpackConfig.externals(nodeExternals({ allowlist: /\.(css|vue)$/ }))
webpackConfig.optimization.splitChunks(false).minimize(false)
webpackConfig.plugins.delete("hmr")
webpackConfig.plugins.delete("preload")
webpackConfig.plugins.delete("prefetch")
webpackConfig.plugins.delete("progress")
webpackConfig.plugins.delete("friendly-errors")
}
and this is my server.jsx file
/* eslint-disable #typescript-eslint/no-var-requires */
const express = require("express")
const path = require("path")
const { createSSRApp } = require("vue")
const { renderToString } = require("#vue/server-renderer")
const manifest = require("../dist/ssr-manifest.json")
const server = express()
const appPath = path.join(__dirname, "../dist", manifest["app.js"])
const App = require(appPath).default
server.get("*", async (_req, res) => {
const content = createSSRApp(App)
const appContent = await renderToString(content)
const html = `
<html>
<head>
<title>Hello</title>
</head>
<body>
${appContent}
</body>
</html>
`
res.end(html)
})
server.listen(8080)
Thank you guys
Try updating your Vue 3 version.
My #vue/server-renderer package was 3.2.20 and my Vue version was 3.2.6. I bumped my Vue version to 3.2.20 and it's working great now. :)
The code is this and when I try to turn my bot on I get a error that it can't find the file to execute the command.
const fs = require('fs');
module.exports = (client, Discord) =>{
const commandFolders = fs.readdirSync('./commands')
for(const folder [enter image description here][1]of commandFolders){
const command_files = fs.readdirSync(`./commands/${folder}`).filter(file => file.endsWith('.js'))
for(const file of command_files){
const command = require(`./commands/${folder}/${file}`);
if(command.name){
client.commands.set(command.name, command);
}else {
continue
}
}
}
}
This is the error I get when I turn my bot on.
node:internal/modules/cjs/loader:944
throw err;
^
Error: Cannot find module './commands/Fun/8ball.js'
Require stack:
- C:\Users\Desktop\Discordproject\handlers\command_handler.js
- C:\Users\Desktop\Discordproject\index.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:941:15)
at Function.Module._load (node:internal/modules/cjs/loader:774:27)
at Module.require (node:internal/modules/cjs/loader:1013:19)
at require (node:internal/modules/cjs/helpers:93:18)
at module.exports (C:\Users\Desktop\Discordproject\handlers\command_handler.js:8:25)
at C:\Users\famil\Desktop\Discordproject\index.js:11:37
at Array.forEach (<anonymous>)
at Object.<anonymous> (C:\Users\Desktop\Discordproject\index.js:10:38)
at Module._compile (node:internal/modules/cjs/loader:1109:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1138:10) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\\Users\Desktop\\Discordproject\\handlers\\command_handler.js',
'C:\\Users\\Desktop\\Discordproject\\index.js'
]
}
Directory Structure:
Your command_handler.js file is inside /handlers/. ./ is used to access the current directory.
Doing ./commands/ doesn't work because the commands folder is not inside of /handlers/
You must first exit the current folder (using ../), then access.
Change all of the './commands' to '../commands'
I have made this utility which i want to import in another file :
const fetch = require('node-fetch');
/**
* #todo Add documentation
*/
class SimplicateApi {
constructor(key,secret){
this._key = key;
this._secret = secret;
this.baseUrl = 'https://simplicate.nl/api/v2';
this.options = {
headers: {
'Content-Type': 'application/json',
'Authentication-Key' : this._key,
'Authentication-Secret' : this._secret
}
}
}
get(endpoint) {
return fetch(`${this.baseUrl}${endpoint}`, this.options)
.then(res => res.json())
.then(json => json);
}
}
export default SimplicateApi;
In another file im importing it like this :
import SimplicateApi from '../../utils/SimplicateApi';
The error I receive :
(function (exports, require, module, __filename, __dirname) { import
{SimplicateApi} from '../../utils/SimplicateApi';
^
SyntaxError: Unexpected token {
at new Script (vm.js:80:7)
at createScript (vm.js:274:10)
at Object.runInThisContext (vm.js:326:10)
at Module._compile (internal/modules/cjs/loader.js:664:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
at startup (internal/bootstrap/node.js:283:19) PS C:\Users\klmaa\OneDrive\Bureaublad\dexhub\client\src\components\cmInf
I removed everything even the fetch and just exported the class like this :
// import fetch from 'node-fetch';
/**
* #todo Add documentation
*/
class SimplicateApi {
}
export default SimplicateApi;
Now im importing it like this :
import SimplicateApi from '../../utils/SimplicateApi';
The error still looks like :
(function (exports, require, module, __filename, __dirname) { import SimplicateApi from '../../utils/SimplicateApi';
^^^^^^^^^^^^^
SyntaxError: Unexpected identifier
at new Script (vm.js:80:7)
at createScript (vm.js:274:10)
at Object.runInThisContext (vm.js:326:10)
at Module._compile (internal/modules/cjs/loader.js:664:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
at startup (internal/bootstrap/node.js:283:19)
PS C:\Users\klmaa\OneDrive\Bureaublad\dexhub\client\src\components\cmInf
Your code is mixing both CommonJs module and ES6 module.
In react, you should use ES6 module.
CommonJs module does not supported by React.You need to configure Babel for this.
const fetch = require('node-fetch'); // this wronng import syntax in React.
Changes should be
// if you are in react.
import fetch from 'node-fetch'; // for react
//if you are in Node.
class SimplicateApi {
}
module.exports = SimplicateApi;
Trying to implement SSR with Firebase so I'm using a function to prerender each page of a React App. It's working well except the home page, so it must be either the match is wrong on the firebase redirect or possibly on the express route itself.
firebase.json
{
"firestore": {
"rules": "firestore.rules",
"indexes": "firestore.indexes.json"
},
"functions": {
"predeploy": [
"npm --prefix \"$RESOURCE_DIR\" run lint"
]
},
"hosting": {
"public": "build",
"rewrites": [
{
"source": "**",
"function": "contentServer"
}
],
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
]
}
}
contentServer.js
import * as functions from 'firebase-functions';
import * as fs from 'fs';
import * as path from 'path';
import React from 'react';
import Helmet from 'react-helmet';
import { renderToString } from 'react-dom/server';
import Server from '../browser/Server.js';
const express = require('express');
const app = express();
// might be this? Also tried /**
app.get(['**'], (request, response) => {
const context = {};
const location = request.url;
console.log('Processing request for ', location);
let appCode;
try {
appCode = renderToString(<Server context={context} location={location} />);
} catch (err) {
appCode = 'with error';
}
// const appState = {
// pageTitle: 'Hello World',
// };
// const preloadedState = JSON.stringify(appState).replace(/</g, '\\u003c');
const fileName = path.join(__dirname, '../index.html');
const htmlTemplate = fs.readFileSync(fileName, 'utf8');
const head = Helmet.renderStatic();
const responseString = htmlTemplate
.replace('<div id="root"></div>', `<div id="root">${appCode}</div>`)
.replace('<title>React App</title>', `${head.title}\n${head.link}`);
return response.send(responseString);
});
export default functions.https.onRequest(app);
Curl
I run firebase serve --only functions,hosting
Then use curl to check the response:
curl http://localhost:5000 - does not render the home page - just the standard react page
curl http://localhost:5000/ - also does not work - just the standard react page.
curl http://localhost:5000/contact-us - works well and returns the contact us page, all other pages on the site work and trigger the function.
If you want redirect every single URL to your host to an express app in Cloud Functions, you will need to do the following:
Make sure there is no index.html in your public hosting folder (otherwise it will always be served with the path /).
Configure Firebase hosting in firebase.json to rewrite all urls to a function (you are currently doing this in your "hosting" block, which is good):
"rewrites": [
{
"source": "**",
"function": "contentServer"
}
]
Write a Cloud Function exported with the same name as the function in the rewrite, and attach an express app that handles the route wildcarded with *. In index.js in your functions folder, minimally:
const functions = require('firebase-functions')
const express = require('express')
const app = express()
app.get("*", (request, response) => {
response.send("OK")
})
exports.contentServer = functions.https.onRequest(app)
If you run this locally with firebase serve --only hosting,functions, every path that you send to localhost:5000 will say "OK".
I have this simple app made using the last alpha version of Koa. In order to use `async/wait Babel.Js is required.
'use strict';
// babel registration (runtime transpilation for node)
require('./server.babel');
const Koa = require('koa');
const app = new Koa();
// define logger - this will be always executed
const logger = async (context, next) => {
const start = new Date;
await next();
const ms = new Date - start;
console.log(`${context.method} ${context.url} - ${ms}ms`);
}
const index = (context) => {
context.body = 'Hello World';
}
app.use(logger);
app.use(index);
app.listen(3000);
console.info(`The app is listening on port 3000`);
This is the hook to activate the transpiling.
const fs = require('fs');
let config;
try {
config = JSON.parse(fs.readFileSync('./.babelrc'));
} catch (error) {
console.error('==> ERROR: Error parsing your .babelrc.');
console.error(error);
}
require('babel-core/register')(config);
and this is the config file:
{
"plugins": ["transform-async-to-generator"]
}
Unfortunately when I try to run the project I get the following error:
const logger = async (context, next) => {
^
SyntaxError: Unexpected token (
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:404:25)
at Object.Module._extensions..js (module.js:432:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:313:12)
at Function.Module.runMain (module.js:457:10)
at startup (node.js:138:18)
at node.js:974:3
I have no idea why I get this error. I'm using the last Node.Js version 5.1.0 and Babel 6.2.1
You are getting the SyntaxError. That happens because your code is being parsed before Babel can intercept it and convert.
If you want to make async functions work in your first file, you should require this entire file after have registered its hook.
Create a new file start.js with the following
require('babel-register');
require('./index');
Your code in index.js can use async functions, but you can't do it in the start.js.
Also note, that you don't need to read .babelrc by yourself. Babel will do it for you by default.
Contents of .babelrc looks like this
{
"presets": [
"es2015",
"stage-3"
],
"plugins": [
[
"transform-runtime",
{
"polyfill": false,
"regenerator": true
}
]
]
}
Reference links
Async Functions with Babel
babel's require hook
upgrade nodejs version to v7.6.0 or higher