Built code errors in Electron: Failed to execute 'querySelector' on 'Document' - vue.js

Using Vite to build the app, I am getting the following error inside Electron:
index.c160f204.js:9 DOMException: Failed to execute 'querySelector' on 'Document': 'link[href="/C:UsersrankDocumentsSchoolCheckInElectronReaderdist/assets/Home.b0f26e4d.js"]' is not a valid selector.
It appears to me that the path inside the built code has the slashes removed, but I have no idea on how to solve that since it's generated code.
Using Node 17.9.0 on Windows 11 10.0.22000 Build 22000
Electron main.js:
const { app, BrowserWindow } = require("electron");
const path = require("path");
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
},
});
win.loadFile("dist/index.html");
}
app.whenReady().then(() => {
createWindow();
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
Electron preload.js:
window.addEventListener("DOMContentLoaded", () => {
const replaceText = (selector, text) => {
const element = document.getElementById(selector);
if (element) element.innerText = text;
};
for (const type of ["chrome", "node", "electron"]) {
replaceText(`${type}-version`, process.versions[type]);
}
});
Vite.config.ts:
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
import * as path from "path";
// https://vitejs.dev/config/
export default defineConfig({
base: path.resolve(__dirname, './dist'),
plugins: [
vue(),
],
})
Using vue-tsc --noEmit && vite build to build and electron . to start.

If you copy/paste the faulty code into a browser console, you will notice a non UTF-8 character in your link, between Users and rank.
Get rid of it and it should work.
The simplest way to fix this would be to move the project to a path which doesn't contain weird chars (e.g: C:/projects/)

Related

Load SVGs components in storybook VUE not working

Hello everyone I'm using vue 3 with storybook 6.5.16 and when i import the SVGs as a component using svg-inline-loader i get the following error in storybook app:
enter image description here
(Failed to execute 'createElement' on 'Document' svg is not a valid name)
Storybook main.js
const path = require('path');
module.exports = {
stories: [
'../src/**/*.stories.mdx',
'../src/**/*.stories.#(js|jsx|ts|tsx)',
],
addons: [
'#storybook/addon-links',
'#storybook/addon-essentials',
'#storybook/addon-interactions',
],
framework: '#storybook/vue3',
core: {
builder: '#storybook/builder-webpack5',
},
webpackFinal: async (config, { configType }) => {
// `configType` has a value of 'DEVELOPMENT' or 'PRODUCTION'
config.module.rules.push({
test: /\.scss$/,
use: [
'style-loader',
'css-loader',
{
loader: "sass-loader",
options: {
additionalData: `
#import "#/assets/scss/main.scss";
`,
implementation: require('sass'),
},
},
],
});
(() => {
const ruleSVG = config.module.rules.find(rule => {
if (rule.test) {
const test = rule.test.toString();
const regular = /\.(svg|ico|jpg|jpeg|png|apng|gif|eot|otf|webp|ttf|woff|woff2|cur|ani|pdf)(\?.*)?$/;
const regularString = regular.toString();
if (test === regularString) {
return rule;
}
}
});
ruleSVG.test = /\.(ico|jpg|jpeg|png|apng|gif|eot|otf|webp|ttf|woff|woff2|cur|ani|pdf)(\?.*)?$/;
})();
config.module.rules.push({
test: /\.svg$/,
use: ['svg-inline-loader'],
});
config.resolve.alias['#'] = path.resolve('src');
return config;
},
}
package.json file
enter image description here
SVG Vue components
<template>
<div
ref="icon"
class="v-icon"
#click="onClick"
>
<component
:is="iconName"
class="v-icon__svg"
/>
</div>
</template>
<script>
import Cards from '#/assets/icons/Cards.svg';
export default {
name: 'VIcon',
components: {
Cards,
},
props: {
iconName: {
type: String,
required: true,
},
},
};
</script>
.babelrc file
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
i tried to use vue-svg-loader to replace svg-inline-loader but it didn't work and I got another error while building the app
ModuleBuildError: Module build failed: Error: Cannot find module './Block'
I also tried to use babel-loader in conjunction with vue-svg-loader but unfortunately I also got an error:
enter image description here
has anyone come across this or can you show your use cases of using SVGs components in Storybook and Vue 3?

How to mock SVG's when snapshot testing with vitest and Storybook?

I am trying to run vitest snapshot tests on Storybook stories using the composeStories Fn from #storybook/testing-react, but I keep getting the error:
FAIL src/components/common/Nav/Nav.test.tsx > Nav Component > it should match the snapshot
Error: Element type is invalid: expected a string (for built-in components) or a class/function
(for composite components) but got: undefined. You likely forgot to export your component from
the file it's defined in, or you might have mixed up default and named imports.
Check the render method of `Nav`.
//... stack trace
I believe it's related to the svg imports, as this only occurs in components that import svgs as react components via the SVGR library. i.e.
// components/common/Nav.tsx
import { ReactComponent as ECDLogo } from '#assets/ecd_logo.svg';
And my vite.config.ts uses the vite-svgr-plugin:
// vite.config.ts
import { defineConfig } from 'vite';
import react from '#vitejs/plugin-react';
import svgr from 'vite-plugin-svgr';
import tsconfigPaths from 'vite-tsconfig-paths';
import path from 'path';
const tsConfigPathsOpts = {
extensions: ['.svg', '.png', '.jpeg'],
loose: true,
};
export default defineConfig({
build: {
outDir: 'build',
},
define: {
global: {},
},
resolve: {
alias: {
'#': path.resolve(__dirname, './src'),
'#assets': path.resolve(__dirname, './src/assets'),
'#styles': path.resolve(__dirname, './src/styles'),
'#types': path.resolve(__dirname, './src/types'),
'#components': path.resolve(__dirname, './src/components'),
},
},
plugins: [react(), svgr(), tsconfigPaths(tsConfigPathsOpts)],
});
My Storybook config (.storybook/main.js) looks like so:
const path = require('path');
const { mergeConfig } = require('vite');
const tsconfigPaths = require('vite-tsconfig-paths');
const svgr = require('vite-plugin-svgr');
const tsConfigPathsOpts = {
extensions: ['.svg', '.png', '.jpeg'],
loose: true,
};
module.exports = {
stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.#(js|jsx|ts|tsx)'],
addons: [
'#storybook/addon-essentials',
'#storybook/preset-create-react-app',
'#storybook/addon-a11y',
'#storybook/node-logger',
'storybook-addon-designs',
'storybook-color-picker',
'storybook-dark-mode',
],
framework: '#storybook/react',
core: {
builder: '#storybook/builder-vite',
},
async viteFinal(config, { configType }) {
return mergeConfig(config, {
resolve: {
alias: {
'#': path.resolve(__dirname, '../src'),
'#assets': path.resolve(__dirname, '../src/assets'),
'#styles': path.resolve(__dirname, '../src/styles'),
'#types': path.resolve(__dirname, '../src/types'),
'#components': path.resolve(__dirname, '../src/components'),
},
},
plugins: [svgr(), tsconfigPaths.default(tsConfigPathsOpts)],
});
},
};
I've come to understand that I need to mock these SVG's so that their snapshot is consistent, but I need direction on whether my mocking implementation is correct. See the vi.mock Fn below.
// components/common/Nav/Nav.test.tsx
import React from 'react';
import { render } from '#testing-library/react';
import '#testing-library/jest-dom/extend-expect';
import { composeStories } from '#storybook/testing-react';
import * as stories from './Nav.stories'; // import all stories from the stories file
import { vi } from 'vitest';
const { NavDefault } = composeStories(stories);
👀
vi.mock('#assets/*', () => {
return {
default: 'SVGUrl',
ReactComponent: 'div',
};
});
describe('Nav Component', () => {
test('it should match the snapshot', () => {
const { asFragment } = render(<NavDefault />);
expect(asFragment()).toMatchSnapshot();
});
});
I was expecting this to mock all the imports from #assets/* to be strings "SVGUrl" or 'div'
But I get the same error as above:
FAIL src/components/common/Nav/Nav.test.tsx > Nav Component > it should match the snapshot
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
we had the same issue today and fixed it by adding the plugin svgr() in vitest.config.ts
import svgr from "vite-plugin-svgr";
export default defineConfig({
plugins: [
// ...other plugins
svgr(),
]
})

import { ipcRenderer } from 'electron' produces this error: __dirname is not defined

With this simple vue page:
<template>
<div class="home">
<HelloWorld msg="Welcome to Your Vue.js App"/>
</div>
</template>
<script>
import HelloWorld from '#/components/HelloWorld.vue'
import { ipcRenderer } from 'electron'
export default {
name: 'Home',
components: {
HelloWorld
},
data() {
return {
dato: null
}
},
methods: {
rendererFunct () {
//ipcRenderer.on('setting', (event, arg) => {
//console.log(arg);
//})
}
}
}
</script>
The only presence of import { ipcRenderer } from 'electron' produces the error __dirname is not defined :
Is this problem is something related to webpack configuration or it is due to something else?
This is my webpack.config.js :
import 'script-loader!./script.js';
import webpack from 'webpack';
const path = require('path');
const CopyPlugin = require('copy-webpack-plugin');
module.exports = {
target: ['electron-renderer', 'electron-main', 'electron-preload'],
pluginOptions: {
electronBuilder: {
chainWebpackMainProcess: config => {
config.resolve.alias.set('jsbi', path.join(__dirname, 'node_modules/jsbi/dist/jsbi-cjs.js'));
}
},
},
};
module.exports = {
entry: './src/background.js',
target: 'node',
output: {
path: path.join(__dirname, 'build'),
filename: 'backend.js'
}
}
module.exports = config => {
config.target = "electron-renderer";
return config;
};
module.exports = {
plugins: [
new CopyPlugin({
patterns: [
{ from: 'source', to: 'dest' },
{ from: 'other', to: 'public' },
],
options: {
concurrency: 100,
},
}),
],
};
module.exports = {
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
'style-loader',
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader',
],
},
],
},
};
const supportedLocales = ['en-US', 'it'];
export default const config = {
plugins: [
new webpack.ContextReplacementPlugin(
/date\-fns[\/\\]/,
new RegExp(`[/\\\\\](${supportedLocales.join('|')})[/\\\\\]index\.js$`)
)
]
}
This is vue.config.js :
module.exports = {
configureWebpack: {
// Configuration applied to all builds
},
pluginOptions: {
electronBuilder: {
chainWebpackMainProcess: (config) => {
// Chain webpack config for electron main process only
},
chainWebpackRendererProcess: (config) => {
config.plugin('define').tap((args) => {
args[0]['IS_ELECTRON'] = true
return args
})
},
mainProcessFile: 'src/background.js',
mainProcessWatch: ['src/preload.js'],
}
}
}
module.exports = {
pluginOptions: {
electronBuilder: {
disableMainProcessTypescript: false,
mainProcessTypeChecking: false
}
}
}
Electron: version 9.0.0
webpack: version 4.44.1
System:
OS: Linux 5.4 Ubuntu 18.04.4 LTS (Bionic Beaver)
CPU: (8) x64 Intel(R) Core(TM) i7-4790K CPU # 4.00GHz
Binaries:
Node: 14.5.0 - ~/.nvm/versions/node/v14.5.0/bin/node
Yarn: 1.22.4 - /usr/bin/yarn
npm: 6.14.5 - ~/.nvm/versions/node/v14.5.0/bin/npm
Browsers:
Chrome: 84.0.4147.105
Firefox: 79.0
Looking forward to your kind help.
Marco
__dirname is a NodeJS variable, in recent electron versions, node integration is disabled by default. When opening your BrowserWindow, you should add the following to the options:
webpreferences:{
nodeIntegration: true
}
This is however STRONGLY DISCOURAGED as this opens up security issues.
this seems to solve it for most people (for me sadly enough i now get the next error:
fs.existsSync is not a function)
a better solution i to change your bundler to the correct build mode. You should not be building for node but for web, so target:esnext or something.
if something requires node access, this should be solved by running it in the background thread or the preload scripts.
You can apply the solution described on this post
How to import ipcRenderer in vue.js ? __dirname is not defined
In this way you can call this method from vue files:
window.ipcRenderer.send(channel, args...)
Just make sure you configure preload.js on vue.config.js:
// vue.config.js - project root
module.exports = {
pluginOptions: {
electronBuilder: {
preload: 'src/preload.js' //make sure you have this line added
}
}
}

Show updated PWA created in Vue

I uasing Vue.js with Vuetify and creating a PWA.
I have service-worker.js in /public folder
A snippet from vue.config.js:
pwa: {
// configure the workbox plugin
workboxPluginMode: 'InjectManifest',
workboxOptions: {
// swSrc is required in InjectManifest mode.
swSrc: 'public/service-worker.js',
// ...other Workbox options...
}
}
This looks too be working good and caching the shell etc.
I run build and serve up the project
npm run build
The problem i have is when i update any files, i can't see the updated changes.
when i navigate to the url in my android device the page remains as the old one (cached).
How can i get it to update?
I tried including this code in index.html, but no success:
https://developers.google.com/web/tools/workbox/guides/advanced-recipes#offer_a_page_reload_for_users
service-worker.js
importScripts("/precache-manifest.8812c20b1b3401cbe039782d13cce03d.js", "https://storage.googleapis.com/workbox-cdn/releases/3.6.3/workbox-sw.js");
console.log(`Hello from service worker`);
if (workbox) {
console.log(`Workbox is loaded`);
self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.precaching.suppressWarnings();
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});
addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {
skipWaiting();
}
});
}
else {
console.log(`Workbox didn't load`);
}
Not sure what exactly your setup setup is, but it should be similar. Using the #vue/cli-plugin-pwa and with minimal setup below.
This will show a dialog when a new version of your app is available. Clicking yes will update your app. You will have to refresh the page somehow to actually show the new version, but that is up to you on how solve that.
vue.config.js:
module.exports = {
pwa: {
name: "name-of-your-app",
short_name: "noya",
themeColor: "#000000",
workboxPluginMode: "InjectManifest",
workboxOptions: {
swSrc: "src/service-worker.js" // CHECK CORRECT PATH!
}
}
};
src/main.js:
import Vue from "vue";
import App from "./App.vue";
import "./registerServiceWorker";
// whatever other imports...
new Vue({
render: h => h(App)
}).$mount("#app");
src/registerServiceWorker.js:
import { register } from "register-service-worker";
if (process.env.NODE_ENV === "production") {
register(`${process.env.BASE_URL}service-worker.js`, {
updated(registration) {
if (window.confirm("A new version is available, update now?")) {
const worker = registration.waiting;
worker.postMessage({ action: "SKIP_WAITING" });
// refresh the page or trigger a refresh programatically!
}
}
});
}
src/service-worker.js:
self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.precaching.suppressWarnings();
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});
self.addEventListener("message", (event) => {
if (event.data.action == "SKIP_WAITING") self.skipWaiting();
});
I get it work by following the offer_a_page_reload_for_users. The original registerServiceWorker.js seems redundant though.
src/registerServiceWorker.js
import { Workbox } from "workbox-window";
if (process.env.NODE_ENV === "production" && "serviceWorker" in navigator) {
const wb = new Workbox("/service-worker.js");
wb.addEventListener("waiting", () => {
const result = window.confirm("refresh now?");
if (result) {
wb.messageSW({ type: "SKIP_WAITING" });
}
});
wb.addEventListener("controlling", () => {
window.location.reload();
});
wb.register();
}

how to fix blank page if i am using vue router with electron js?

I'm trying to use vue router with an application on an Electron JS. If I use a router on the render page, then the router work done. But I do not understand how to make the transition to the page, for example,- 'Settings' using the Tray. At attempt of transition the empty page opens.
I have prepared a working example of the project. This problem exists only build project. In development mode all work well.
This is my work example on github. Please need help.
git clone https://github.com/DmtryJS/electron-vue-example.git
cd electron-vue-example
npm install
npm run build
and run dist\win-unpacked\example_for_stackoverflow.exe
my main.js file
'use strict'
import { app, protocol, BrowserWindow, Menu, ipcMain, Tray } from 'electron'
import { format as formatUrl } from 'url'
const electron = require('electron');
const path = require('path');
const isDevelopment = process.env.NODE_ENV !== 'production';
let imgBasePath;
if(isDevelopment) {
imgBasePath = path.join('src','assets', 'img');
} else {
imgBasePath = path.join(path.dirname(__dirname), 'extraResources', 'img');
}
let win;
let tray;
protocol.registerStandardSchemes(['app'], { secure: true })
const trayIcon = path.join(__static, 'img', 'icon.png');
function createWindow () {
win = new BrowserWindow({
width: 800,
height: 600,
icon: trayIcon
})
routeTo(win, "")
win.on('closed', () => {
win = null
})
//убрать меню
win.setMenuBarVisibility(true)
win.on('show', function() {
tray.setHighlightMode('always')
})
win.on('hide', function() {
tray.setHighlightMode('never')
})
}
// Quit when all windows are closed.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (win === null) {
createWindow()
}
})
app.on('ready', () => {
createWindow()
win.webContents.openDevTools(); //открыть dev tools
createTray()
})
// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
if (process.platform === 'win32') {
process.on('message', data => {
if (data === 'graceful-exit') {
app.quit()
}
})
} else {
process.on('SIGTERM', () => {
app.quit()
})
}
}
function createTray()
{
let traiIconPath = path.join(imgBasePath, 'preloader_tray_icon.png')
tray = new Tray(traiIconPath)
const contextMenu = Menu.buildFromTemplate(
[
{
label: 'Settings',
type: 'normal',
click: function()
{
routeTo(win, "/settings")
let contents = win.webContents
contents.on('dom-ready', function()
{
if(!win.isVisible())
{
showWindow()
}
})
}
},
{
label: 'Exit',
type: 'normal',
click: function()
{
win = null
app.quit()
}
}
])
tray.setContextMenu(contextMenu)
tray.on('click', function() {
toggleWindow();
})
}
function showWindow() {
var position = getPosition();
win.setPosition(position.x, position.y, false)
win.show()
win.focus()
}
ipcMain.on('routerEvent', function(event, arg) {
routeTo(win, arg)
})
function routeTo(win, to) {
if (isDevelopment) {
win.loadURL(`http://localhost:${process.env.ELECTRON_WEBPACK_WDS_PORT}` + to)
} else {
win.loadURL(formatUrl({
pathname: path.join(__dirname, 'index.html' + to);,
protocol: 'file',
slashes: true
}))
}
}
And
router.js
import Vue from 'vue'
import Router from 'vue-router'
import Main from './../views/Main.vue'
import Settings from './../views/Settings.vue'
Vue.use(Router)
export default new Router({
//mode: 'history',
routes: [
{
path: '/',
name: 'home',
component: Main
},
{
path: '/settings',
name: 'settings',
component: Settings
}
]
})
You need to add created to the main Vue app check docs
// src/main.js
new Vue({
router,
render: h => h(App),
created() {
// Prevent blank screen in Electron builds
this.$router.push('/')
}
}).$mount('#app')
The solution for me was to remove the history mode in the vue router.
Sorry, but after one day of googling, I just found a solution. The case turned out to be
win.loadURL(formatUrl({
pathname: path.join(__dirname, 'index.html' + to);,
protocol: 'file',
slashes: true
}))
I delete formaUrl and everything works well
win.loadURL(path.join(__dirname, 'index.html' + to));
For me solution was this:
Check if app is running at addresses like this:
Local: http://x86_64-apple-darwin13.4.0:8080/
Network: http://localhost:8080/
Check if you can access x86_64..url in browser. If you are not seeing a webpage but can see it from localhost, then map 127.0.0.1 to x86_64-apple-darwin13.4.0 in hosts file. in mac its located in /etc/hosts in windows its in system32/drivers/etc.