I tried to test a react-native component but I got this error.
I realize that the error comes from import Convertor, { ConvertorComponent } from '../components/Convertor.js declared in the convertor.test.js file. I exported the component with export ConvertorComponent and with export default Convertor.
const warnedKeys: {[string]: boolean} = {};
SyntaxError: Missing initializer in const declaration
at ScriptTransformer.transformAndBuildScript (node_modules/#jest/transform/build/ScriptTransformer.js:471:17)
at ScriptTransformer.transform (node_modules/#jest/transform/build/ScriptTransformer.js:513:25)
at Object.<anonymous> (node_modules/react-native/Libraries/react-native/react-native-implementation.js:14:18)
Related
I am just practicing creating a GitHub app. Part of the Octokit it says that I can use the createNodeMiddleware. Now that might not necessarily be as simple with next.js; however, the problem that I am having is actually a compiler error (it seems) where it says that it cannot read properties of undefined (reading 'substr') when I am trying to just create a new instance of the App object.
Here is my code
import { Octokit, App } from "octokit";
// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
const myApp = new App({
appId: 123,
privateKey: "",
});
return NextResponse.redirect(new URL('/about-2', request.url))
}
// See "Matching Paths" below to learn more
export const config = {
matcher: '/about/:path*',
}
When it executes the line for const myApp = new App({... it throws this error. Any ideas on where to start with this? I realize that I may need to manually make the routes that it creates with the middleware in the end. But I was hoping to at least be able to create an instance of the App with Octokit as it seems like that will be necessary no matter what functionality that I want from octokit. This is a nextjs app bootstraped with create-next-app and the typescript template.
Server Error
TypeError: Cannot read properties of undefined (reading 'substr')
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
<unknown>
node_modules\universal-user-agent\dist-web\index.js (6:0)
getUserAgent
node_modules\universal-user-agent\dist-web\index.js (6:26)
eval
node_modules\#octokit\endpoint\dist-web\index.js (359:64)
(middleware)/./node_modules/#octokit/endpoint/dist-web/index.js
evalmachine.<anonymous> (138:1)
__webpack_require__
evalmachine.<anonymous> (37:33)
fn
evalmachine.<anonymous> (269:21)
eval
webpack-internal:///(middleware)/./node_modules/#octokit/request/dist-web/index.js (5:75)
(middleware)/./node_modules/#octokit/request/dist-web/index.js
evalmachine.<anonymous> (248:1)
__webpack_require__
evalmachine.<anonymous> (37:33)
fn
evalmachine.<anonymous> (269:21)
eval
webpack-internal:///(middleware)/./node_modules/#octokit/core/dist-web/index.js (8:74)
I have an Express app built in TypeScript that I'm attempting to compile using the tsc CLI tool.
An issue that I'm facing, however, is that tsc seems to ignore the index.d.ts file that I've created and used to mutate the Express Request object.
This is my index.d.ts file:
declare global{
namespace Express{
export interface Request{
foo: string;
}
}
}
This allows me to do stuff like this inside my controller's requests without TypeScript spitting out a does not exist error:
export const example = async (req: Request) => {
const { foo } = req;
// Outputs "bar". This works completely fine in development.
console.log(foo);
};
I'm running the following command to build my app:
tsc ./Main.ts --outdir build
Which results in the following error multiple times across every controller that uses it:
error TS2339: Property 'foo' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.
Try adding an empty export to your index.d.ts file:
export {};
declare global{
namespace Express{
export interface Request{
foo: string;
}
}
}
I was following the tutorial on https://github.com/mxstbr/passport-magic-login, but it keeps yelling at me "TypeError: MagicLoginStrategy is not a constructor" when running the code. Following is my code.
#auth.js
import MagicLoginStrategy from "passport-magic-login"
const magicLogin = new MagicLoginStrategy({...});
export default magicLogin;
#app.js
import magicLogin from './auth.js';
...
passport.use(magicLogin);
Why does it keep yelling the error? I also checked the MagicLoginStrategy, it was as follows.
class MagicLoginStrategy {
private _options;
...
constructor(_options: Options);
...
}
export default MagicLoginStrategy;
I think i'm calling the right constructor, and I don't know why I'm facing the errors.
Thanks in advance.
import MagicLoginStrategy from "passport-magic-login";
const magicLogin = new MagicLoginStrategy.default();
It's loading the CommonJS dist file instead of the ESM file.
const MagicLoginStrategy = require('passport-magic-login').default
there is an issue about it
https://github.com/mxstbr/passport-magic-login/issues/7 ;
I'm sorry for my poor English skills.
I created a new project using express-generator-typescript.
$ npx express-generator-typescript --use-yarn
I want to add additional properties to Express.Request for my custom middleware.
So I created types/myRequest.d.ts in ./src and put and save the code as below:
// myRequest.d.ts
declare namespace Express {
interface Request {
myProp?: boolean;
}
}
And I uncommented "typeRoots" in tsconfig.json and added "./node_modules/#types", "./src/types", and I tried to use the added property by creating a some middleware in ./src/routes/api.ts. Here's the full code:
// api.ts
import { NextFunction, Request, Response, Router } from "express";
import userRouter from "./user-router";
function myMiddleware(req: Request, _res: Response, next: NextFunction) {
req.myProp = true;
next();
}
// Export the base-router
const baseRouter = Router();
// Setup routers
baseRouter.use("/users", myMiddleware, userRouter);
// Export default.
export default baseRouter;
This builds fine, also IntelliSense in VS Code works fine and doesn't show any issues. However, when I run yarn start:dev I get the following error:
/home/me/dev/express-gen-ts/node_modules/ts-node/src/index.ts:828
return new TSError(diagnosticText, diagnosticCodes);
^
TSError: ⨯ Unable to compile TypeScript:
src/routes/api.ts:5:7 - error TS2339: Property 'myProp' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.
5 req.myProp = true;
~~~~~~
at createTSError (/home/me/dev/express-gen-ts/node_modules/ts-node/src/index.ts:828:12)
at reportTSError (/home/me/dev/express-gen-ts/node_modules/ts-node/src/index.ts:832:19)
at getOutput (/home/me/dev/express-gen-ts/node_modules/ts-node/src/index.ts:1022:36)
at Object.compile (/home/me/dev/express-gen-ts/node_modules/ts-node/src/index.ts:1326:43)
at Module.m._compile (/home/me/dev/express-gen-ts/node_modules/ts-node/src/index.ts:1458:30)
at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Object.require.extensions.<computed> [as .ts] (/home/me/dev/express-gen-ts/node_modules/ts-node/src/index.ts:1462:12)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19) {
diagnosticCodes: [ 2339 ]
}
[nodemon] app crashed - waiting for file changes before starting...
So I can't do development in dev state. Of course if I don't use additional properties, the dev state is also available and works fine.
I think express-generator-typescript itself has some setting. Because changing "typeRoots" in tsconfig.json doesn't change the result. But I couldn't find it.
Thank you in advance.
Whenever I run into this type of problem, I usually use "declare module" to add properties to Express's "Request" interface instead of declaring them in a namespace. This way I usually don't have to change anything in the tsconfig nor add any .d.ts files.
Add these lines to your api.ts code (note that in most cases you will need to reference the express-serve-static-core module as this is where the Request interface is declared):
declare module "express-serve-static-core" {
interface Request {
myProp?: boolean;
}
}
Full file:
// api.ts
import { NextFunction, Request, Response, Router } from "express";
import userRouter from "./user-router";
declare module "express-serve-static-core" {
interface Request {
myProp?: boolean;
}
}
function myMiddleware(req: Request, _res: Response, next: NextFunction) {
req.myProp = true;
next();
}
// Export the base-router
const baseRouter = Router();
// Setup routers
baseRouter.use("/users", myMiddleware, userRouter);
// Export default.
export default baseRouter;
Normally this should make your newly added property available in other files as well, but you can of course export the manipulated Request interface just to be safe.
I suggest you a way and hope it helps you.
in the file ./src/routes/api.ts you add this code (under import)
declare global {
namespace Express {
interface Request {
myProp?: boolean;
}
}
}
then run again (doesn't seem to need types/myRequest.d.ts file)
When I run a jest test, creating a Pool instance when I require the pool, it returns a _pg.Pool is not a constructor error.
I have tried looking at the StackOverflow: pg.Pool is not a constructor
And this still does not work.
However, I am able to create a pool instance when I run the code, the error only shows up in Jest.
Node code:
import { Pool } from 'pg'
const pool = new Pool({configs})
export default pool
Error log:
● Test suite failed to run
TypeError: _pg.Pool is not a constructor
> 6 | const pool = new Pool({
|
at Object.<anonymous> (src/resources/connection.js:6:14)
at Object.require (src/routes/api.js:2:20)
at Object.<anonymous> (src/__tests__/integration/user.test.js:8:1)
sidenote: the code is a copy of the documentation in https://node-postgres.com/api/pool
I don't expect an error to occur, since pg.Pool is a class with a constructor.
In case anyone comes across the same problem, I solved it by installing pg-pool, which has been merged into main pg package, and then importing pg-pool's Pool instead of pg's.
Reference: https://github.com/brianc/node-postgres/tree/master/packages/pg-pool
I wanted to add an alternate answer because for me the issue was very subtle and simple to fix.
I have a wrapper module that leverages pg and which historically has imported it via:
import * as postgresql from 'pg';
I've always used this.pool = new postgresql.Pool( { ...bits } );
This of course led to the following error today when updating my module to be pure ESM:
TypeError: postgresql.Pool is not a constructor
at new PostgreSQLDriver (file:///home/rik/workspaces/kwaeri/node-kit/postgresql-database-driver/dist/src/postgresql-database-driver.mjs:35:278)
at file:///home/rik/workspaces/kwaeri/node-kit/postgresql-database-driver/dist/test/postgresql-database-driver.mjs:23:559
at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:528:24)
at async importModuleDynamicallyWrapper (node:internal/vm/module:438:15)
at async formattedImport (/home/rik/workspaces/kwaeri/node-kit/postgresql-database-driver/node_modules/mocha/lib/nodejs/esm-utils.js:7:14)
at async exports.loadFilesAsync (/home/rik/workspaces/kwaeri/node-kit/postgresql-database-driver/node_modules/mocha/lib/nodejs/esm-utils.js:91:20)
at async singleRun (/home/rik/workspaces/kwaeri/node-kit/postgresql-database-driver/node_modules/mocha/lib/cli/run-helpers.js:125:3)
at async exports.handler (/home/rik/workspaces/kwaeri/node-kit/postgresql-database-driver/node_modules/mocha/lib/cli/run.js:370:5)
I tried using named exports as the documentation seems to suggest in the Check, use, return section, but that got me:
file:///home/rik/workspaces/kwaeri/node-kit/postgresql-database-driver/dist/src/postgresql-database-driver.mjs:23
cov_1u3o9s5ali=function(){return actualCoverage;};}return actualCoverage;}cov_1u3o9s5ali();import{Pool}from'pg';import{DatabaseDriver}from'#kwaeri/database-driver';// You'll need this line and the method definitions below
^^^^
SyntaxError: Named export 'Pool' not found. The requested module 'pg' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:
import pkg from 'pg';
const {return actualCoverage;};}return actualCoverage;}cov_1u3o9s5ali();import{Pool}from'pg';import{DatabaseDriver} = pkg;
... As I had actually expected it would.
Anyways, the fix is hinted to by typescript in the syntax error above - doh:
import Postgres from `pg`;
// ...
this.pool = new Postgres.Pool( { ...bits } );
That resolves the issue.