Why is contextBridge not being imported in my Electron app? - node.js

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.

Related

Fixing Webpack's Watch Option

I had code that worked just fine, but now I've updated some packages, especially webpack, and I'm getting some warnings that I'd like to remove.
When I run the command npm run watch, I get the following error:
[DEP_WEBPACK_WATCH_WITHOUT_CALLBACK] DeprecationWarning: A 'callback' argument need to be provided to the 'webpack(options, callback)' function when the 'watch' option is set. There is no way to handle the 'watch' option without a callback.
My package.json is as follows:
{
"name": "simple-flask-react-template",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack -p --progress --config webpack.config.js",
"dev-build": "webpack --progress -d --config webpack.config.js",
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "webpack --progress -d --config webpack.config.js --watch"
},
"author": "jadiker",
"license": "None",
"homepage": "https://github.com/rbarbaresco/simple-flask-react-template#readme",
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"bootstrap": "^4.2.1",
"css-loader": "^2.1.0",
"file-loader": "^3.0.1",
"jquery": "^3.5.1",
"popper.js": "^1.14.7",
"react": "^16.7.0",
"react-dom": "^16.7.0",
"webpack": "^5.11.1",
"webpack-cli": "^3.3.10"
},
"babel": {
"presets": [
"env",
"react"
]
},
"dependencies": {
"#fortawesome/fontawesome-svg-core": "^1.2.28",
"#fortawesome/free-solid-svg-icons": "^5.13.0",
"#fortawesome/react-fontawesome": "^0.1.9",
"query-string": "^6.11.1",
"react-router-dom": "^5.1.2"
}
}
My webpack.config.js is as follows:
const webpack = require('webpack');
const config ={
mode: 'development',
entry: {
login: './js/login.jsx',
signup: './js/signup.jsx',
index: './js/index.jsx',
search: './js/search.jsx',
ask: './js/ask.jsx',
question: './js/question.jsx',
help: './js/help.jsx',
test: './js/test.jsx',
},
devtool: 'inline-source-map',
output: {
path: __dirname + '/dist/bundle',
filename: '[name].bundle.js',
},
resolve:{
extensions:[
'.js',
'.jsx',
'.css'
]
},
module:{
rules:[
{
test:/\.jsx?/,
exclude:/node_modules/,
use:'babel-loader'
},
{
test:/\.(jpe?g|png|gif|svg)$/i,
loader:"file-loader",
},
{
test:/\.css$/,
use:[
'css-loader'
],
},
]
}
};
module.exports = config;
What can I change in the code in order to get that warning to go away?

node js webpack Undefined envioronment variable

HHHi,
I'm trying to use the .env file to store the API id and key for the API I'm using and it's not working. My .env file is in the root of my working directory as well as the root of the repository where the .gitignore file is. It looks like this:
API_ID=XXXXXX
API_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXX
I installed dotenv and in my index.js file in my server directory I call it like this:
const dotenv = require('dotenv');
dotenv.config();
then in my apiCall.js function I try to call the variables from the .env file like this:
const AYLIENTextAPI = require('aylien_textapi');
let textapi = new AYLIENTextAPI({
application_id: process.env.API_ID,
application_key: process.env.API_KEY
});
but the ID and Key are showing up as undefined. What am I doing wrong? I would really appreciate any help.
Thanks,
Mike
UPDATE:
this is my webpack.dev.js file:
const path = require('path')
const webpack = require('webpack')
const HtmlWebPackPlugin = require("html-webpack-plugin")
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
module.exports = {
entry: './src/client/index.js',
output : {
libraryTarget: 'var',
library: 'Client'
},
mode: 'development',
devtool: 'source-map',
stats: 'verbose',
module: {
rules: [
{
test: '/\.js$/',
exclude: /node_modules/,
loader: "babel-loader"
},
{
test: /\.scss$/,
use: [ 'style-loader', 'css-loader', 'sass-loader' ]
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/client/views/index.html",
filename: "./index.html",
}),
new CleanWebpackPlugin({
// Simulate the removal of files
dry: true,
// Write Logs to Console
verbose: true,
// Automatically remove all unused webpack assets on rebuild
cleanStaleWebpackAssets: true,
protectWebpackAssets: false
})
]
}
this is my package.json file:
{
"name": "example-project",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node src/server/index.js",
"build-prod": "webpack --config webpack.prod.js",
"build-dev": "webpack --config webpack.dev.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"aylien_textapi": "^0.7.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"webpack": "^4.41.6",
"webpack-cli": "^3.3.11"
},
"devDependencies": {
"#babel/core": "^7.8.4",
"#babel/preset-env": "^7.8.4",
"babel-loader": "^8.0.6",
"clean-webpack-plugin": "^3.0.0",
"css-loader": "^3.4.2",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.9.0",
"node-sass": "^4.13.1",
"optimize-css-assets-webpack-plugin": "^5.0.3",
"sass-loader": "^8.0.2",
"style-loader": "^1.1.3",
"terser-webpack-plugin": "^2.3.5",
"webpack-dev-server": "^3.10.3",
"workbox-webpack-plugin": "^5.0.0"
}
}
figured it out. I can only access the environment variables on the server side.

Code spliting with dynamic imports still create big files

I'm trying to make a production version about my client side code to deploy later in AWS. When I compile and build my web application in development enviromet, everything works fine. But when I try to do it in production enviroment I've got a warning because I've got files bigger than 244KB.
To fix this problem, I have been following the indications of Dynamic Imports But, how you can see in this screen cap, I'm still getting a file very big:
My application use Node.js, React.js and webpack 4. This is my package.json
{
"name": "basketmetrics3",
"version": "1.0.0",
"description": "Basketball advanced stats",
"main": "server.js",
"scripts": {
"dev-webpack": "webpack-dev-server --hot --mode development",
"clean": "rm -rf ./dist",
"dev": "npm run build-dev && cross-env NODE_ENV=development nodemon --exec babel-node src/server/server.js --ignore ./src/client",
"build-dev": "npm run clean && npm run compile-dev",
"compile-dev": "NODE_ENV=development webpack -d --config ./webpack.config.babel.js --progress",
"compile": "NODE_ENV=production webpack -p --config ./webpack.config.babel.js --progress",
"build": "npm run clean && npm run compile",
"start": "npm run build && node ./dist/assets/js/main.bundle.js",
"heroku-postbuild": "webpack -p"
},
"dependencies": {
"#babel/polyfill": "^7.4.4",
"#material-ui/core": "^3.9.3",
"#material-ui/icons": "^3.0.2",
"bootstrap": "^4.3.1",
"cors": "^2.8.5",
"create-react-app": "^3.0.1",
"cross-env": "^5.2.0",
"d3": "^5.9.7",
"dotenv": "^7.0.0",
"express": "^4.17.1",
"express-graphql": "^0.7.1",
"graphql": "^14.4.2",
"jquery": "^3.4.1",
"morgan": "^1.9.1",
"mysql2": "^1.6.5",
"popper.js": "^1.15.0",
"react": "^16.8.6",
"react-bootstrap": "^1.0.0-beta.10",
"react-bootstrap-table-next": "^3.1.7",
"react-bootstrap-table2-paginator": "^2.0.7",
"react-dom": "^16.8.6",
"react-multi-language": "^0.4.2",
"react-router-dom": "^5.0.1",
"react-simple-tooltip": "^2.6.1",
"sequelize": "^4.44.2",
"validator": "^10.11.0"
},
"devDependencies": {
"#babel/cli": "^7.5.5",
"#babel/core": "^7.5.5",
"#babel/node": "^7.5.5",
"#babel/preset-env": "^7.5.5",
"#babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.6",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-register": "^6.26.0",
"css-loader": "^2.1.1",
"file-loader": "^3.0.1",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.5.0",
"nodemon": "^1.19.1",
"path": "^0.12.7",
"style-loader": "^0.23.1",
"url-loader": "^1.1.2",
"webpack": "^4.38.0",
"webpack-cli": "^3.3.6",
"webpack-dev-server": "^3.7.2"
}
}
To run my application in development enviroment I do it with this command: npm run dev and to run my application in production environment I do it with npm run start.
And this is my webpack.config.babel.js:
import path from "path";
import HtmlWebpackPlugin from "html-webpack-plugin";
import MiniCssExtractPlugin from "mini-css-extract-plugin";
const devMode = process.env.NODE_ENV !== "production";
console.log("devMode: " + devMode);
module.exports = {
entry: "./src/client/index.js", //set entry file
// Resolve to output directory and set file
output: {
path: path.resolve("dist/assets"),
filename: "js/[name].bundle.js",
chunkFilename: "js/[name].bundle.js",
publicPath: "/assets" //It's mandatory to define this publicPath to get access to the website when we reload pages
//or we access to them directly with url's which have directories of second level like
//http://localhost:4000/directory-level-1/directory-level-2
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/client/index.html", //where is our template
filename: "../index.html", //where we are going to put our index.html inside the output directory
minify: {
collapseWhitespace: true,
removeComments: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
useShortDoctype: true
}
}),
new MiniCssExtractPlugin({
filename: "css/bundle.css",
minify: {
collapseWhitespace: true,
removeComments: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
useShortDoctype: true
}
})
],
//It help us to detect errors.
devtool: "source-map",
// Set dev-server configuration
devServer: {
inline: true,
contentBase: './dist',
port: 3000
},
// Add babel-loader to transpile js and jsx files
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use:[
{
loader: "babel-loader",
query: {
presets: [
"#babel/preset-react"
]
}
}
]
},
{
use: [
devMode ? "style-loader" : MiniCssExtractPlugin.loader,
"css-loader"],
test: /\.css$/
},
{
test: /\.scss$/,
use: [
{
loader: "style-loader"
},
{
loader: "css-loader",
options: {
sourceMap: true
}
},
{
loader: "saas-loader",
options: {
sourceMap: true
}
}
]
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: "url-loader",
options: {
limit: 10000,
publicPath: "/assets/images/",
outputPath: "./images/"
}
},
{
test: /\.(eot|ttf|woff|woff2)$/,
loader: "url-loader",
options: {
limit: 10000,
publicPath: "/assets/fonts/", //It's mandatory to get access to the fonts when we reload pages or access directly
outputPath: "./fonts/"
}
}
]
}
}
How can I split my code in files smaller than the file that I've got in this moment?
Edit I (solved):
One possible solution to split the client code in files with a size smaller than 244Kb could be adding this entry to webpack.config.babel.js file:
optimization: {
splitChunks : {
chunks: "all",
minSize: 30000,
maxSize: 100000,
}
},
Now, I've got several files with a size smaller than 100Kb. Any other option to do the same?

Express JS with Webpack giving cannot find module error

Hi I am new with frontend technologies so I have a question around webpack and express js. I am building an application using react , webpack , node and express js. The app.js looks like the following
app.js
const express = require('express');
const app = express();
var path = require('path');
app.use(express.static(__dirname + '/'));
app.get('/', (req, res) => { // new
res.sendFile(__dirname + "/index.html");
});
app.listen(3000, () => console.log('listening on port 3000'));
package.json looks like following
"version": "1.0.0",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 0",
"build": "webpack --mode production",
"start": "nohup webpack-dev-server --mode development --open &",
"prepublishOnly": "cp -r configuration/* build/"
},
"repository": {
"type": "git",
"url": "ssh://git.amazon.com/pkg/SPSWebApplication"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.3.4",
"#babel/preset-env": "^7.3.4",
"#babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.5",
"express": "^4.16.4",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"react-dom": "^16.8.4",
"webpack": "^4.29.6",
"webpack-cli": "^3.3.0",
"webpack-dev-middleware": "^3.6.1",
"webpack-dev-server": "^3.2.1"
},
"dependencies": {
"#stencil-react/core": "*",
"#stencil-react/theme-default": "*",
"webpack": "^4.29.6",
"webpack-cli": "^3.3.0",
"react": "^16.8.4",
"webpack-dev-server": "^3.2.1",
"html-webpack-plugin": "^3.2.0"
},
"description": ""
}
webpack.config.js
const HtmlWebPackPlugin = require("html-webpack-plugin");
module.exports = {
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
use: [
{
loader: "html-loader",
options: { minimize: true }
}
]
}
]
},
resolve: { // this allows to import 'Foo.jsx'
extensions: ['.jsx', '.js', '.json']
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
})
]
};
when i build the code in the build folder it creates dist/app.js,main.js,index.html whenever i try to run app.js it says
Error: Cannot find module 'express'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:649:15)
at Function.Module._load (internal/modules/cjs/loader.js:575:25)
at Module.require (internal/modules/cjs/loader.js:705:19)
at require (internal/modules/cjs/helpers.js:14:16)
I want to run my application in production environment through dist/app.js but when I do "node app.js" it gives me this dependency issue I am assuming webpack should pull the express dependency in dist/* folder in a minified form which i am assuming it is not doing. Can you please if I am missing anything and my understanding is correct or not?

Invalid configuration object -configuration.output.path after installing sass

I facing an issue while running webpack using the command npm run dev, after installing npm sass
"node-sass": "^4.5.2",
"sass-loader": "^6.0.3",
"style-loader": "^0.16.1",
Issue:
Invalid configuration object -configuration.output.path.
given my package.json and webpack.config.js.
Thanks in advance could somebody let me know what we went wrong, how could we resolve this issue.
Issue:
webpack.config.js
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/app.js',
output: {
path : ' dist',
filename : 'app.bundle.js'
},
module: {
rules: [
{ test: /\.scss$/, use: ['style-loader','css-loader', 'sass-loader'] }
]
},
plugins: [
new HtmlWebpackPlugin({
title: 'Index Project Template',
minify: {
collapseWhitespace: true
},
hash: true,
template: './src/indextemp.ejs', // Load a custom template (ejs by default see the FAQ for details)
})
]
}
package.json
{
"name": "webpacks",
"version": "1.0.0",
"description": "Webpack Start",
"main": "index.js",
"scripts": {
"dev": "webpack -d --watch",
"prod": "webpack -p"
},
"author": "",
"license": "ISC",
"devDependencies": {
"css-loader": "^0.28.0",
"html-webpack-plugin": "^2.28.0",
"node-sass": "^4.5.2",
"sass-loader": "^6.0.3",
"style-loader": "^0.16.1",
"webpack": "^2.4.1"
}
}

Resources