So i did a fresh install of nestjs application and i am trying to add the serverless framework with it.I also added few of the packages to support the serverless framework
{
"name": "n1",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"#hewmen/serverless-plugin-typescript": "^1.1.17",
"#nestjs/common": "^7.0.0",
"#nestjs/core": "^7.0.0",
"#nestjs/platform-express": "^7.0.0",
"aws-lambda": "^1.0.6",
"aws-serverless-express": "^3.3.8",
"express": "^4.17.1",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^6.5.4",
"serverless-offline": "^6.5.0",
"serverless-plugin-optimize": "^4.1.4-rc.1"
},
"devDependencies": {
"#nestjs/cli": "^7.0.0",
"#nestjs/schematics": "^7.0.0",
"#nestjs/testing": "^7.0.0",
"#types/express": "^4.17.3",
"#types/jest": "25.2.3",
"#types/node": "^13.9.1",
"#types/supertest": "^2.0.8",
"#typescript-eslint/eslint-plugin": "3.0.2",
"#typescript-eslint/parser": "3.0.2",
"eslint": "7.1.0",
"eslint-config-prettier": "^6.10.0",
"eslint-plugin-import": "^2.20.1",
"jest": "26.0.1",
"prettier": "^1.19.1",
"supertest": "^4.0.2",
"ts-jest": "26.1.0",
"ts-loader": "^6.2.1",
"ts-node": "^8.6.2",
"tsconfig-paths": "^3.9.0",
"typescript": "^3.7.4"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
and i have also added the serverless.yml file which is pointing in to lambda.handler
serverless.yml file
service:
name: nest-serverless-framework
plugins:
- '#hewmen/serverless-plugin-typescript'
- serverless-plugin-optimize
- serverless-offline
provider:
name: aws
runtime: nodejs12.x
functions:
main:
handler: src/lambda.handler
events:
- http:
method: any
path: /{any+}
So the handler file is simple it just exported a module that can bootstrap the application
import { Handler, Context } from 'aws-lambda';
import { Server } from 'http';
import { createServer, proxy } from 'aws-serverless-express';
import { eventContext } from 'aws-serverless-express/middleware';
import { NestFactory } from '#nestjs/core';
import { ExpressAdapter } from '#nestjs/platform-express';
import { AppModule } from './app.module';
import express from 'express';
const binaryMimeTypes: string[] = [];
let cachedServer: Server;
// Create the Nest.js server and convert it into an Express.js server
async function bootstrapServer(): Promise<Server> {
if (!cachedServer) {
const expressApp = express();
const nestApp = await NestFactory.create(AppModule, new
ExpressAdapter(expressApp))
nestApp.use(eventContext());
await nestApp.init();
cachedServer = createServer(expressApp, undefined,
binaryMimeTypes);
}
return cachedServer;
}
// Export the handler : the entry point of the Lambda function
export const handler: Handler = async (event: any, context: Context) => {
cachedServer = await bootstrapServer();
return proxy(cachedServer, event, context, 'PROMISE').promise;
}
but when i now try to do sls offline start, the computer just hangs and nothing happen and i have to restart the computer forcefully.
Any help would be appreciated.
I had a similar issue with v8 crashing during the serverless build. Changing packages from #hewmen/serverless-plugin-typescript to the original serverless-plugin-typescript fixed it.
Please note that aws-serverless-express says:
On 11/30 [2022], the AWS Serverless Express library is moving to Vendia and will be rebranded to serverless-express [...]
has become obsolete.
Probably the same job, you wanted to achieve, does the following Vendina example:
vendia serveless basic-starter-nestjs
Related
I am trying to run my sveltekit app, it was running fine few day's back but suddenly now when I run
"npm run build" it throw error Error: Not found: /, the way I understand is it is couldn't find entry file for app
// my vite.config file
// vite.config.js
import { sveltekit } from '#sveltejs/kit/vite';
/** #type {import('vite').UserConfig} */
const config = {
plugins: [sveltekit()]
};
export default config;
// my package.json
{
"name": "first-pwa",
"version": "0.0.1",
"scripts": {
"dev": "vite dev",
"build": "vite build",
"package": "vite package",
"preview": "vite preview",
"test": "playwright test",
"lint": "prettier --ignore-path .gitignore --check --plugin-search-dir=. . && eslint --ignore-path .gitignore .",
"format": "prettier --ignore-path .gitignore --write --plugin-search-dir=. ."
},
"devDependencies": {
"#playwright/test": "^1.21.0",
"#sveltejs/adapter-auto": "^1.0.0-next.34",
"#sveltejs/adapter-static": "^1.0.0-next.29",
"#sveltejs/kit": "^1.0.0-next.314",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-svelte3": "^3.4.1",
"leaflet": "^1.8.0",
"prettier": "^2.6.2",
"prettier-plugin-svelte": "^2.7.0",
"sass": "^1.50.0",
"svelte": "^3.47.0",
"svelte-leafletjs": "^0.9.0",
"svelte-preprocess": "^4.10.6",
"svelte-range-slider-pips": "^2.0.3",
"svelte-simple-datatables": "^0.2.3",
"vanillajs-datepicker": "^1.2.0",
"vite": "^3.0.4"
},
"type": "module",
"dependencies": {
"#glidejs/glide": "^3.5.2",
"#sveltejs/adapter-node": "^1.0.0-next.73",
"bootstrap": "^5.1.3",
"bootstrap-icons": "^1.8.1",
"bootswatch": "^5.1.3",
"chartist": "^0.11.4",
"popper": "^1.0.1",
"svelte-loadable": "^2.0.1",
"svelte-speedometer": "^1.1.0",
"sveltestrap": "github:laxadev/sveltestrap",
"ua-parser-js": "^1.0.2"
}
}
I haven't migrated to the latest sveltekit changes yet I want my old app up running first,it would be very helpful if anyone could help me with this
I have tried adding entry path in vite.config.js but it didn't help
import { defineConfig } from 'vite';
import { sveltekit } from '#sveltejs/kit/vite';
/** #type {import('vite').UserConfig} */
export default defineConfig({
plugins: [sveltekit()]
build: {
lib: {
entry: 'src/routes/index.svelte'
}
}
});
Pages have been renamed from index.svelte to +page.svelte. When you rename your routes they should be detected without a custom entry file configuration.
I'm following the NestJS documentation on how to set up a fastify/apollo server with nest but after adding fastify to main.ts I get this error:
FastifyError: fastify-plugin: fastify-accepts - expected '3.x' fastify version, '4.6.0' is installed
I've tried installing fastify 3.x, changing versions of other modules but according to yarn.lock some modules need 3.x and others need 4.x.
These are the docs I'm following:
https://docs.nestjs.com/techniques/performance
https://docs.nestjs.com/graphql/quick-start
Here is my main.ts
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app.module';
import {
FastifyAdapter,
NestFastifyApplication,
} from '#nestjs/platform-fastify';
import { ValidationPipe } from '#nestjs/common';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter({ logger: true }),
);
app.useGlobalPipes(new ValidationPipe());
await app.listen(3000);
console.log(`Application is running on: ${await app.getUrl()}`);
}
bootstrap();
Here is my package.json
{
"name": "app",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"#nestjs/apollo": "^10.1.0",
"#nestjs/common": "^9.0.0",
"#nestjs/core": "^9.0.0",
"#nestjs/graphql": "^10.1.2",
"#nestjs/platform-express": "^9.0.0",
"#nestjs/platform-fastify": "^9.1.1",
"apollo-server-fastify": "^3.10.2",
"class-transformer": "^0.5.1",
"class-validator": "^0.13.2",
"firebase-admin": "^11.0.1",
"graphql": "^16.6.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.2.0",
"ts-morph": "^16.0.0"
},
"devDependencies": {
"#nestjs/cli": "^9.0.0",
"#nestjs/schematics": "^9.0.0",
"#nestjs/testing": "^9.0.0",
"#types/express": "^4.17.13",
"#types/jest": "28.1.8",
"#types/node": "^16.0.0",
"#types/supertest": "^2.0.11",
"#typescript-eslint/eslint-plugin": "^5.0.0",
"#typescript-eslint/parser": "^5.0.0",
"eslint": "^8.0.1",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"jest": "28.1.3",
"prettier": "^2.3.2",
"source-map-support": "^0.5.20",
"supertest": "^6.1.3",
"ts-jest": "28.0.8",
"ts-loader": "^9.2.3",
"ts-node": "^10.0.0",
"tsconfig-paths": "4.1.0",
"typescript": "^4.7.4"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
#nestjs/common#^9 and #nestjs/platform-fastify#^9 require you to use fastify#^4. However, apllo-server-fastify does not support fastify#^4 and will not until apollo-server v4 comes out. Until then,. you can follow the docs and use mercurius instead.
Your other option would be to downgrade to #nestjs/common#^8 and #nestjs/platform-fastify#^8 along with #nestjs/graphql#^9 which supports fastify#^3
I'm trying to archive an entire folder using Node, archiver and fs, but nothing seems to happen.
This is my implementation:
import { createWriteStream } from 'fs';
import archiver from 'archiver';
await zipDirectory('./work', './work/folderName.zip');
const zipDirectory = async (source: string, out: string): Promise<void> => {
const archive = archiver('zip', { zlib: { level: 9 }});
return new Promise((resolve, reject) => {
const stream = createWriteStream(out);
archive
.directory(source, false)
.on('error', err => reject(err))
.pipe(stream);
stream.on('close', () => resolve());
archive.finalize();
});
}
Running on Node 14.15.4
Package.json
{
"name": "rpj",
"version": "1.0.0",
"description": "",
"main": "./dist/src/main.js",
"author": "David Faizulaev",
"license": "ISC",
"scripts": {
"start": "node ./dist/main.js",
"build": "yarn build:js",
"build:prod": "yarn run build:js",
"build:types": "tsc --emitDeclarationOnly",
"build:js": "babel . --out-dir ./dist --extensions \".ts\" --ignore node_modules --ignore dist --source-maps",
"build-ts": "tsc",
"test": "jest --coverage --verbose",
"lint-test": "npm run lint && npm run test",
"lint": "eslint -c .eslintrc.js --ext .ts ./src",
"lint:fix": "eslint --fix -c .eslintrc.js --ext .ts ./src",
"tslint": "tslint -c tslint.json --project tsconfig.json",
"sonar": "node ./config/sonar-project.js",
"prettier": "prettier --write ./projects/**/*.*",
"sonar-dev": "node ./config/sonar-dev-project.js"
},
"dependencies": {
"archiver": "^5.3.0",
"aws-sdk": "2.861.0",
"cheerio": "^1.0.0-rc.5",
"config": "3.3.6",
"esm": "^3.2.25",
"express": "^4.17.1",
"imagemin": "7.0.1",
"imagemin-mozjpeg": "^9.0.0",
"imagemin-pngquant": "^9.0.2",
"jszip": "3.6.0",
"lodash": "4.17.21",
"node-request-context": "^1.0.5",
"uuid": "^8.3.2",
"winston": "^3.3.3"
},
"devDependencies": {
"#babel/cli": "7.13.10",
"#babel/core": "7.13.10",
"#babel/plugin-proposal-class-properties": "7.13.0",
"#babel/plugin-proposal-object-rest-spread": "7.13.8",
"#babel/plugin-transform-runtime": "7.13.10",
"#babel/preset-env": "7.13.10",
"#babel/preset-typescript": "7.13.0",
"#babel/runtime": "7.13.10",
"#types/archiver": "^5.1.1",
"#types/config": "0.0.38",
"#types/express": "^4.17.11",
"#types/imagemin": "7.0.1",
"#types/imagemin-mozjpeg": "^8.0.1",
"#types/jest": "^26.0.20",
"#types/node": "14.14.33",
"#types/uuid": "^8.3.0",
"#typescript-eslint/eslint-plugin": "4.17.0",
"#typescript-eslint/eslint-plugin-tslint": "4.17.0",
"#typescript-eslint/parser": "4.17.0",
"aws-sdk-mock": "5.1.0",
"eslint": "7.21.0",
"eslint-config-prettier": "^6.11.0",
"eslint-plugin-jest": "^23.18.0",
"eslint-plugin-jsdoc": "32.2.0",
"jest": "27",
"lint-staged": "^10.5.3",
"sonarqube-scanner": "^2.8.0",
"ts-jest": "27",
"ts-node": "10",
"tslint": "^6.1.3",
"typescript": "4.4.4"
}
}
Please advise on how I can resolve this?
Issue was caused because I did not create the directory to where I wanted to store the zip file.
Once I added the directory creation at startup everything worked.
There are loads of threads on this issue, none of which have solutions that work for me.
I am using NestJS, TypeORM, and Cosmos DB Mongo API.
I am running the NestJS service on my machine, hitting the Database in Azure.
I can read from collections fine, but any time I try to write, I get the following error:
MongoError: Retryable writes are not supported. Please disable retryable writes by specifying "retrywrites=false" in the connection string or an equivalent driver specific config.
A stripped down version of the logic that is saving to the DB. The object I am saving works fine when doing db.collection.save() in Mongo Shell in Azure. But the exact same save() fails here
#Injectable()
export class PatientService {
constructor(
#InjectRepository(PatientsByUser)
private readonly patientsByUserRepo: MongoRepository<PatientsByUser>
) {}
async addPatientToFavoritesList() {
this.patientsByUserRepo.save({
email: "test",
patientList: [{
accountNumber: 1,
firstName: "test",
lastName: "test",
dob: "test"
}]
})
}
}
Here is the module that configures TypeORM:
import {HttpModule, Module} from '#nestjs/common';
import {ConfigModule} from "#nestjs/config";
import {TypeOrmModule} from "#nestjs/typeorm";
import {PatientService} from "./patient.service";
import {PatientController} from "./patient.controller";
import {PatientsByUser} from "./patient.entity";
#Module({
imports: [
HttpModule,
ConfigModule.forRoot(),
TypeOrmModule.forRoot({
type: 'mongodb',
url: process.env.MONGODB_CONNECTION_STRING,
database: process.env.MONGODB_DATABASE,
entities: [
__dirname + '/**/*.entity{.ts,.js}',
],
ssl: true,
useUnifiedTopology: true,
useNewUrlParser: true,
}),
TypeOrmModule.forFeature([PatientsByUser])
],
providers: [PatientService],
controllers: [PatientController],
exports: [PatientService]
})
export class PatientModule {}
My connection string does contain retrywrites=false. I also tried retryWrites=false, and tried both at the end of the connection string. Neither worked.
MONGODB_CONNECTION_STRING=mongodb://portal-db-dev:<private>==#portal-db-dev.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=#portal-db-dev#
Our Cosmos DB is version 4. I am aware that rolling back to 3.2 would fix this, but that would be suboptimal, and completely absurd on Microsoft's part if thats the only way out of this.
package.json
{
"name": "portal-be",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build && mkdir dist/src/assets && cp -r src/assets/* dist/src/assets",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"#nestjs/common": "^7.6.13",
"#nestjs/config": "^0.6.3",
"#nestjs/core": "^7.6.13",
"#nestjs/passport": "^7.1.5",
"#nestjs/platform-express": "^7.6.13",
"#nestjs/swagger": "^4.7.15",
"#nestjs/typeorm": "^7.1.5",
"#types/mongodb": "^3",
"#types/passport-azure-ad": "^4.0.8",
"class-transformer": "^0.4.0",
"class-validator": "^0.13.1",
"dotenv": "^8.2.0",
"jwt-decode": "^3.1.2",
"moment": "^2.29.1",
"mongodb": "^3.6.9",
"passport": "^0.4.1",
"passport-azure-ad": "^4.3.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^6.6.7",
"soap": "^0.39.0",
"typeorm": "^0.2.32"
},
"devDependencies": {
"#nestjs/cli": "^7.5.6",
"#nestjs/schematics": "^7.2.7",
"#nestjs/testing": "^7.6.13",
"#types/express": "^4.17.11",
"#types/jest": "^26.0.20",
"#types/mongodb": "^3",
"#types/node": "^14.14.31",
"#types/supertest": "^2.0.10",
"#typescript-eslint/eslint-plugin": "^4.15.2",
"#typescript-eslint/parser": "^4.15.2",
"eslint": "^7.20.0",
"eslint-config-prettier": "^8.1.0",
"eslint-plugin-prettier": "^3.3.1",
"jest": "^26.6.3",
"prettier": "^2.2.1",
"supertest": "^6.1.3",
"ts-jest": "^26.5.2",
"ts-loader": "^8.0.17",
"ts-node": "^9.1.1",
"tsconfig-paths": "^3.9.0",
"typescript": "^4.1.5"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
Cosmos DB doesn't support retryable writes.
The mongo shell does not enable retryable writes by default.
MongoDB drivers compatible with MongoDB 4.2 or newer enable retryable writes by default.
The MongoDB Node.JS driver versions 3.3+ are compatible with MongoDB 4.2
To connect to a db server that does not support retryable writes using a driver that enables retryable writes by default, you will need to disable retryable writes by passing retryWrites=false in the connection string URI.
https://docs.mongodb.com/manual/core/retryable-writes/#enabling-retryable-writes
I Have the same problem, but with mongorestore
In the connection string I tried retryWrites=false and retrywrites=false
and the problem persists.
I found and answer that works for me, --writeConcern="{w:0}"
posted here: Mongorestore from localhost to cosmosDb fails with "disable retryable writes by specifying "retrywrites=false"
I'm writing an Electron app with React and Typescript, using Webpack, Babel and ESLint but I'm having trouble setting:
mainWindow = new BrowserWindow({
title: "Biomech",
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
enableRemoteModule: false,
sandbox: true,
preload: path.join(__dirname, "./preload.js"),
nativeWindowOpen: true,
},
});
which I want as a security measure.
The reason being that, if I set the webPreferences as specified above, I need to use contextBridge and a preload script that binds the functions that are using IPC to the window. And the problem is that contextBridge is not being properly imported in my preload.ts:
import { contextBridge, ipcRenderer } from "electron";
import { readFileSync } from 'fs';
import { History } from 'history';
import { LIST_DRIVE_FILES_CHANNEL, LOAD_PREV_TEST_RESULTS_CHANNEL, OAUTH2_ACCESS_TOKEN_REQUEST_CHANNEL } from "../src/constants/ipcChannels";
import { VISUALIZE_RESULTS_PATH } from "../src/constants/urls";
// Expose protected methods that allow the renderer process to use
// the ipcRenderer without exposing the entire object
contextBridge.exposeInMainWorld(
"api", {
exchangeCodeForAccessToken: (code: string) => {
ipcRenderer.invoke(OAUTH2_ACCESS_TOKEN_REQUEST_CHANNEL, code);
},
listDriveFiles: (accessToken: string) => {
ipcRenderer.invoke(LIST_DRIVE_FILES_CHANNEL, accessToken);
},
openDirectoryDialog: (history: History) => {
ipcRenderer.invoke(LOAD_PREV_TEST_RESULTS_CHANNEL).then((dialog: any) => {
if (dialog.canceled) { // canceled with one l is correct
return;
} else {
const selectedDirectory = dialog.filePaths[0];
console.log(readFileSync(selectedDirectory + "/README.md", 'utf-8'));
history.push(VISUALIZE_RESULTS_PATH);
}
})
}
}
);
The way I see it it's properly used like the examples I've seen here in SO, or in the Electron docs. But when I run my main process script: npm run dev:electron which is specified in my package.json:
{
"name": "electron-react-ts-app",
"version": "1.0.0",
"description": "Electron + React + Typescript",
"main": "./dist/main.js",
"preload": "./dist/preload.js",
"scripts": {
"dev": "concurrently --success first \"npm run dev:electron\" \"npm run dev:react\" -k",
"dev:electron": "NODE_ENV=development webpack --config webpack.electron.config.js --mode development && electron .",
"dev:react": "NODE_ENV=development webpack serve --config webpack.react.config.js --mode development",
"build:electron": "NODE_ENV=production webpack --config webpack.electron.config.js --mode production",
"build:react": "NODE_ENV=production webpack --config webpack.react.config.js --mode production",
"build": "npm run build:electron && npm run build:react",
"pack": "electron-builder --dir",
"dist": "electron-builder",
"lint": "eslint .",
"format": "prettier --write \"**/*.+(js|jsx|json|yml|yaml|css|md|vue)\""
},
"keywords": [],
"license": "MIT",
"build": {
"files": [
"dist/",
"node_modules/",
"package.json"
],
"productName": "Example",
"appId": "com.example.app",
"directories": {
"output": "dist"
}
},
"devDependencies": {
"#babel/preset-env": "^7.9.5",
"#babel/preset-react": "^7.9.4",
"#babel/preset-typescript": "^7.9.0",
"#types/electron-devtools-installer": "^2.2.0",
"#types/react-router-dom": "^5.1.7",
"#types/regenerator-runtime": "^0.13.0",
"dpdm": "^3.6.0",
"electron": "^11.2.1",
"electron-builder": "^22.7.0",
"electron-devtools-installer": "^3.1.1",
"eslint": "^7.18.0",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^4.5.1",
"husky": "^4.3.8",
"lint-staged": "^10.5.3",
"prettier": "^2.2.1",
"react-router-dom": "^5.2.0",
"webpack": "^5.11.1",
"webpack-cli": "^4.3.1",
"webpack-dev-server": "^3.11.1"
},
"dependencies": {
"#babel/core": "^7.12.10",
"#popperjs/core": "^2.6.0",
"#types/node": "^14.14.22",
"#types/react": "^17.0.0",
"#types/react-dom": "^17.0.0",
"axios": "^0.21.1",
"babel-loader": "^8.2.2",
"bootstrap": "^4.5.3",
"chokidar": "^3.5.1",
"core-js": "^3.8.3",
"css-loader": "^5.0.1",
"electron-fetch": "^1.7.3",
"fsevents": "^2.3.1",
"ini": "^2.0.0",
"jquery": "^3.5.1",
"react": "^17.0.1",
"react-bootstrap": "^1.4.0",
"react-dom": "^17.0.1",
"react-google-login": "^5.2.2",
"style-loader": "^2.0.0"
},
"husky": {
"hooks": {
"pre-commit": "npm run lint && npm run format"
}
},
"lint-staged": {
"*.+(js|jsx)": "eslint --fix",
"*.+(json|css|md)": "prettier --write"
}
}
I get the following error: Cannot read property 'exposeInMainWorld' of undefined
webpack 5.19.0 compiled successfully in 1793 ms
App threw an error during load
TypeError: Cannot read property 'exposeInMainWorld' of undefined
at Object../electron/preload.ts (/Users/lucas_sg/Documents/ITBA/PF/pf-biomech/dist/preload.js:24:53)
at __webpack_require__ (/Users/lucas_sg/Documents/ITBA/PF/pf-biomech/dist/preload.js:128:41)
at /Users/lucas_sg/Documents/ITBA/PF/pf-biomech/dist/preload.js:252:11
at Object.<anonymous> (/Users/lucas_sg/Documents/ITBA/PF/pf-biomech/dist/preload.js:254:12)
at Module._compile (internal/modules/cjs/loader.js:1152:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1173:10)
at Module.load (internal/modules/cjs/loader.js:992:32)
at Module._load (internal/modules/cjs/loader.js:885:14)
at Function.f._load (electron/js2c/asar_bundle.js:5:12738)
at Module.require (internal/modules/cjs/loader.js:1032:19)
I've checked out this repo regarding Electron security and it doesn't look like he's doing things too different, at least at first glance, but I'm clearly messing something up.
Here's my webpack config (webpack.electron.config.js) in case it's useful:
const path = require("path");
module.exports = [
{
resolve: {
extensions: [".tsx", ".ts", ".js"],
},
devtool: "source-map",
entry: {
main: {
import: "./electron/main.ts",
dependOn: "preload"
},
preload: "./electron/preload.ts"
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "[name].js",
},
target: "electron-main",
module: {
rules: [
{
test: /\.(js|ts|tsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
],
},
node: {
__dirname: false,
},
},
];
I think the issue resides in you webpack.config file:
entry: {
main: {
import: "./electron/main.ts",
dependOn: "preload"
},
preload: "./electron/preload.ts"
},
Might be that webpack tries to resolve all "preload.ts" dependency at compile time, plus tries to bundle it together with main.ts file. And in such case it will never get access to contextBridge. The preload.js file should only be run in a separate "context" - "Isolated World" as they refer in the docs.
What I would try is:
remove the dependOn: and preload: lines from you webpack config.
convert preload.ts file to JS (ie. to CommonJS format) - try doing that with TS CLI for now
Your preload.js file should look more or less like this:
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld(
'electron',
{
doThing: () => ipcRenderer.send('do-a-thing')
}
)
copy preload.js to a __dirname (in my case it was /dist)
run electron again
That was the only way I could access "contextBridge" object.