How add rollupNodePolyFill to electron.vite.configs - electron

I need excute 'twilio-client' on electron project
import Twilio from 'twilio-client';
// this line broken when run electron-vite preview or builded app version
const device = new Twilio.Device();
device.setup('xyls', {
debug: true
});
console.log(device);
When I run my app with electron-vite preview or after build, I got an error:
Uncaught TypeError: Failed to resolve module specifier "events"
This also happened when it was executed:
electron-vite dev --watch
I added nodePolifill plugins now it works in dev mode, but on preview or build doesn't
The plugin 'rollup-plugin-node-polyfills' doesn't works on build.rollupOptions.plugins
I need help
My electron.vite.configs.ts:
import { resolve, normalize, dirname } from 'path'
import { defineConfig } from 'electron-vite'
import injectProcessEnvPlugin from 'rollup-plugin-inject-process-env'
import tsconfigPathsPlugin from 'vite-tsconfig-paths'
import reactPlugin from '#vitejs/plugin-react'
import { NodeGlobalsPolyfillPlugin } from '#esbuild-plugins/node-globals-polyfill'
import { NodeModulesPolyfillPlugin } from '#esbuild-plugins/node-modules-polyfill'
import rollupNodePolyFill from "rollup-plugin-node-polyfills";
import { main, resources } from './package.json'
const [nodeModules, devFolder] = normalize(dirname(main)).split(/\/|\\/g)
const devPath = [nodeModules, devFolder].join('/')
const tsconfigPaths = tsconfigPathsPlugin({
projects: [resolve('tsconfig.json')],
})
export default defineConfig({
main: {
plugins: [tsconfigPaths],
build: {
rollupOptions: {
input: {
index: resolve('src/main/index.ts'),
},
output: {
dir: resolve(devPath, 'main'),
},
},
},
},
preload: {
plugins: [tsconfigPaths],
build: {
outDir: resolve(devPath, 'preload'),
},
},
renderer: {
define: {
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
'process.platform': JSON.stringify(process.platform),
},
server: {
port: 4927,
},
publicDir: resolve(resources, 'public'),
plugins: [
tsconfigPaths,
reactPlugin(),
],
resolve: {
alias: {
util: 'rollup-plugin-node-polyfills/polyfills/util',
sys: 'util',
stream: 'rollup-plugin-node-polyfills/polyfills/stream',
path: 'rollup-plugin-node-polyfills/polyfills/path',
querystring: 'rollup-plugin-node-polyfills/polyfills/qs',
punycode: 'rollup-plugin-node-polyfills/polyfills/punycode',
url: 'rollup-plugin-node-polyfills/polyfills/url',
string_decoder: 'rollup-plugin-node-polyfills/polyfills/string-decoder',
http: 'rollup-plugin-node-polyfills/polyfills/http',
https: 'rollup-plugin-node-polyfills/polyfills/http',
os: 'rollup-plugin-node-polyfills/polyfills/os',
assert: 'rollup-plugin-node-polyfills/polyfills/assert',
constants: 'rollup-plugin-node-polyfills/polyfills/constants',
_stream_duplex: 'rollup-plugin-node-polyfills/polyfills/readable-stream/duplex',
_stream_passthrough: 'rollup-plugin-node-polyfills/polyfills/readable-stream/passthrough',
_stream_readable: 'rollup-plugin-node-polyfills/polyfills/readable-stream/readable',
_stream_writable: 'rollup-plugin-node-polyfills/polyfills/readable-stream/writable',
_stream_transform: 'rollup-plugin-node-polyfills/polyfills/readable-stream/transform',
timers: 'rollup-plugin-node-polyfills/polyfills/timers',
console: 'rollup-plugin-node-polyfills/polyfills/console',
vm: 'rollup-plugin-node-polyfills/polyfills/vm',
zlib: 'rollup-plugin-node-polyfills/polyfills/zlib',
tty: 'rollup-plugin-node-polyfills/polyfills/tty',
domain: 'rollup-plugin-node-polyfills/polyfills/domain',
events: 'rollup-plugin-node-polyfills/polyfills/events',
buffer: 'rollup-plugin-node-polyfills/polyfills/buffer-es6', // add buffer
process: 'rollup-plugin-node-polyfills/polyfills/process-es6', // add process
}
},
optimizeDeps: {
esbuildOptions: {
// Node.js global to browser globalThis
define: {
global: 'globalThis'
},
// Enable esbuild polyfill plugins
plugins: [
NodeGlobalsPolyfillPlugin({
process: true,
buffer: true,
}),
NodeModulesPolyfillPlugin(),
]
}
},
worker: {
format: "es",
},
build: {
outDir: resolve(devPath, 'renderer'),
rollupOptions: {
plugins: [
injectProcessEnvPlugin({
NODE_ENV: 'production',
platform: process.platform,
}),
rollupNodePolyFill() //this line doesn't works
],
input: {
index: resolve('src/renderer/index.html'),
},
output: {
format: "esm",
dir: resolve(devPath, 'renderer'),
},
},
},
},
})
and the is my project repostitory:
https://github.com/caioregatieri/app-electron
I tried add many polyfills, add twilio import on preload and export to render with
contextBridge.exposeInMainWorld('Twilio', Twilio)

I solved it with:
electron.vite.config.ts
build: {
outDir: resolve(devPath, 'renderer'),
rollupOptions: {
plugins: [
injectProcessEnvPlugin({
NODE_ENV: 'production',
platform: process.platform,
}),
rollupNodePolyFill,
],
},
},
and this:
index.html
<script>
global = globalThis;
</script>

Related

Appium - Codeceptjs - Gherkin, can not execute steps script and config failed

I've got some issues with codeceptjs appium.
I run test script by npx codeceptjs run , it did not execute the step_definitions file.
I config steps definition with /*steps.js and its not working, i have to direct exact path of steps file.
The app crashed without throw exception, the script still being execute.
add-task.feature
Feature: Add task
Background: I opened the application
Scenario: Add task
Given I click Add Task button
And I input all information
add-task-steps.js
When("I input all information", () => {
AddTaskScreen.inputTaskName('sdsada')
});
const HomeScreen = require("../screens/home-screen.js")
const { I } = inject();
home-screen-steps.js
Given("I click Add Task button", () => {
HomeScreen.tapAddTaskButton();
});
Details
CodeceptJS version: ^3.3.6
NodeJS Version: 8.15.0
Operating System: Windows 10
webdriverio 7.25.2
Configuration file:
exports.config = {
output: './output',
helpers: {
Appium: {
app: 'Appium/ToDoList.apk',
platform: 'Android',
device: 'emulator-5556'
}
},
include: {
I: './steps_file.js',
env:{
TIMEOUT: 5000,
}
},
mocha: {},
bootstrap: null,
timeout: null,
teardown: null,
hooks: [],
gherkin: {
features: './features/*.feature',
steps: ['./step_definitions/home-screen-steps.js']
},
plugins: {
screenshotOnFail: {
enabled: true
},
tryTo: {
enabled: true
},
retryFailedStep: {
enabled: false
},
retryTo: {
enabled: true
},
eachElement: {
enabled: true
},
pauseOnFail: {}
},
stepTimeout: 10000,
stepTimeoutOverride: [{
pattern: 'wait.*',
timeout: 0
},
{
pattern: 'amOnPage',
timeout: 0
}
],
tests: './*_test.js',
name: 'appium'
}
Thanks in advance. <3
I resolved it by replace waitForElementToBeClickable with waitForElement.
Idk why Codeceptjs not recognize waitForElementToBeClickabe and also not throw any exception.

Import image with vanilla-extract and esbuild

I have a problem with images importing using vanilla-extract and esbuild
my build file:
const { build } = require("esbuild");
const { vanillaExtractPlugin } = require("#vanilla-extract/esbuild-plugin");
(async () => {
await build({
entryPoints: ["src/entry.tsx"],
bundle: true,
minify: true,
sourcemap: true,
platform: "browser",
outfile: "dist/entry.js",
plugins: [vanillaExtractPlugin()],
loader: {
".svg": "file",
},
});
})();
my entry.tsx
import { someStyle } from "./style.css";
console.log(someStyle);
When i importing my image in "css" way
import { style } from "#vanilla-extract/css";
export const someStyle = style({
backgroundColor: "url(./x.svg)",
});
The compiler return error
Could not resolve "./x.svg" (the plugin "vanilla-extract" didn't set a resolve directory)`
If i am trying to import x.svg using the typescript import
import { style } from "#vanilla-extract/css";
import svg from "./x.svg";
export const someStyle = style({
backgroundColor: `url(${svg})`,
});
I have other error
src/style.css.ts:5:16: error: No loader is configured for ".svg" files: src/x.svg'
Is it possible to import images with vanilla-extract modules without marking them as external?
It not working now. Workaround is to use babel
import babel from 'esbuild-plugin-babel';
plugins: [
babel({
filter: /.*.css.ts/,
config: {
presets: ['#babel/preset-typescript'],
plugins: ['#vanilla-extract/babel-plugin'],
},
}),
],

Monaca Editor syntax highlighting is ok, but editor doesn't show any errors

Syntax highlighting is ok, but doesn't show any errors.
Line 5 should show an error in red at end of the line in editor, but not.
Why could that be?
I'm using monaco webpack plugin, with these config.
index.js
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
import 'monaco-editor/esm/vs/basic-languages/javascript/javascript';
import 'monaco-editor/esm/vs/basic-languages/python/python';
monaco.editor.create(document.getElementById('duzenleyici'), {
value: ``,
language: 'python',
theme: 'vs-dark',
wordWrap: true,
automaticLayout: true,
});
webpack-config.js
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
const path = require('path');
module.exports = {
entry: './index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'monaco.js',
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.ttf$/,
use: ['file-loader'],
},
],
},
plugins: [
new MonacoWebpackPlugin({
languages: ['javascript', 'python'],
features: ['find', 'bracketMatching', 'comment', 'folding', 'suggest', 'contextmenu', 'coreCommands', 'codeAction', 'clipboard', 'linesOperations', 'suggest', 'wordHighlighter'],
globalAPI: true,
// publicPath: '/',
}),
],
};
In index.js :
`
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
// validation settings
monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
noSemanticValidation: false,
});
// compiler options
monaco.languages.typescript.javascriptDefaults.setCompilerOptions({
target: monaco.languages.typescript.ScriptTarget.ES6,
allowNonTsExtensions: true
});
`
In webpack-config.js plugins key:
new MonacoWebpackPlugin({
languages: ['javascript', 'typescript']
})

No such file or directory, when using Vite and Antd Pro Layout

No such file or directory, when using Vite and Antd Pro Layout
This is file vite.config.ts:
import { defineConfig } from 'vite';
import reactRefresh from '#vitejs/plugin-react-refresh';
import path from 'path';
import vitePluginImp from 'vite-plugin-imp';
export default defineConfig({
plugins: [
reactRefresh(),
vitePluginImp({
libList: [
{
libName: 'antd',
style: (name) => {
return `antd/lib/${name}/style/index.less`;
},
},
],
}),
],
css: {
preprocessorOptions: {
less: {
javascriptEnabled: true,
modifyVars: {
...{
'primary-color': '#1DA57A',
'link-color': '#1DA57A',
'border-radius-base': '2px',
},
},
},
},
},
resolve: {
alias: [
{
find: /^~/,
replacement: path.resolve(__dirname, 'src'),
},
],
},
optimizeDeps: {
include: ['#ant-design/icons'],
},
});
This is my config to using antd, antd-pro-layout with vite.
But I received the error:
[vite] Internal server error: ENOENT: no such file or directory, open
'/Users/tranthaison/DEV/vite2-react-ts/srcantd/es/style/themes/default.less'
Can someone help me to fix it?
I had some problems when using React + Antd in Vite.
Thanks for #theprimone for the answer. But the answer is incomplete. I will complete the answer here.
First time, add additional config to Less Preprocessor:
Add this config to your vite.config.js file:
{
css: {
preprocessorOptions: {
less: {
javascriptEnabled: true,
},
},
},
}
Second, setting module aliases to fix Less #import problem:
Again, add the following config into your vite.config.js file:
{
resolve: {
alias: [
{ find: /^~/, replacement: "" },
],
},
}
Last, install vite-plugin-imp plugin to solve Antd ES problem:
Install the vite-plugin-imp dependencies:
pnpm add -D vite-plugin-imp
# or
npm i -D vite-plugin-imp
then, setup the plugin in your vite.config.js file:
{
plugins: [
// React plugin here
vitePluginImp({
libList: [
{
libName: "antd",
style: (name) => `antd/es/${name}/style`,
},
],
}),
];
}
The final configuration in vite.config.js file will look like this:
import { defineConfig } from "vite";
import reactRefresh from '#vitejs/plugin-react-refresh';
import vitePluginImp from "vite-plugin-imp";
export default defineConfig({
css: {
preprocessorOptions: {
less: {
javascriptEnabled: true,
},
},
},
resolve: {
alias: [
{ find: /^~/, replacement: "" },
],
},
plugins: [
reactRefresh(),
vitePluginImp({
libList: [
{
libName: "antd",
style: (name) => `antd/es/${name}/style`,
},
],
}),
],
});
Also work with #preact/preset-vite.
Ref:
https://github.com/theprimone/vite-react
https://github.com/ant-design/ant-design/issues/7850
https://github.com/vitejs/vite/issues/2185#issuecomment-784637827
Try to import antd styles like this:
vitePluginImp({
libList: [
{
libName: 'antd',
style: (name) => `antd/es/${name}/style`,
},
],
}),
More usage of Vite + React + Ant Design or other UI Library, this repo theprimone/vite-react might give you more or less inspiration.

Nuxt ssr asyncData axios request not works on page reload

After 5-6 hours of searching for the solution, I start to give up. I have a project with docker, node & nuxt.I would like to share meta tags on FB and for this, I need SSR && vue-meta and for vue-meta I need asyncData.
it works with different api!
async asyncData({ params, $axios, error }) {
const product = await $axios.$get(`https://api.nuxtjs.dev/posts/1`);
return { product };
},
It is working when i navigate to here with nuxt routing, but if i reload the page (just here) then i get a RuntimeError from the nuxt ssr.
SO THE REAL PROBLEM IS I GET A RuntimeError ON PAGE RELOAD ON LOCALHOST
async asyncData({ params, $axios, error }) {
//axios knows the api
//http://localhost:8080/
const product = await $axios.$get(`products/${params.id}`);
return { product };
},
If I try this with Axios then I get this error:
Cannot read property 'data' of undefined
If I try this with #nuxt/http then I get this error
request to http://localhost:8080/products/some-id failed, reason: connect ECONNREFUSED 127.0.0.1:8080
I think the problem is when I push hard reload on this page, then I cannot make requests on localhost but I don't know why and how to solve it.
my nuxt-config.js
export default {
// Disable server-side rendering (https://go.nuxtjs.dev/ssr-mode)
// ssr: false,
// Global page headers (https://go.nuxtjs.dev/config-head)
head: {
title: '',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
{ rel: 'preconnect', href: 'https://fonts.gstatic.com' },
{ rel: 'stylesheet', href: 'https://fonts.googleapis.com/css2?family=Josefin+Sans:wght#300;400;600&display=swap' },
]
},
// Global CSS (https://go.nuxtjs.dev/config-css)
css: [
'#/assets/scss/styles.scss',
// '~node_modules/bootstrap/dist/css/bootstrap.css',
// '~node_modules/bootstrap-vue/dist/bootstrap-vue.css',
],
// Plugins to run before rendering page (https://go.nuxtjs.dev/config-plugins)
plugins: [
'~/plugins/notifier',
'~/plugins/axios',
'~/plugins/dateFilter',
'~/plugins/loading',
],
// Auto import components (https://go.nuxtjs.dev/config-components)
components: true,
// Modules for dev and build (recommended) (https://go.nuxtjs.dev/config-modules)
buildModules: [
'nuxt-lazysizes', //https://github.com/ivodolenc/nuxt-lazysizes
'#aceforth/nuxt-optimized-images', //https://github.com/juliomrqz/nuxt-optimized-images //only build
],
// Modules (https://go.nuxtjs.dev/config-modules)
modules: [
'#nuxtjs/axios',
'#nuxtjs/auth',
'#nuxtjs/style-resources',
'nuxt-i18n',
'bootstrap-vue/nuxt',
'#nuxt/http',
],
styleResources: {
scss: [
// './assets/scss/*.scss',
'#/assets/scss/_variables.scss',
'#/node_modules/bootstrap/scss/_functions.scss',
'#/node_modules/bootstrap/scss/_variables.scss',
'#/node_modules/bootstrap/scss/mixins/_breakpoints.scss',
]
},
bootstrapVue: {
bootstrapCSS: false,
bootstrapVueCSS: false,
icons: false,
},
axios: {
// baseURL: ``, //built by docker compose from API_PORT && API_HOST variables
},
auth: {
strategies: {
local: {
endpoints: {
login: { url: '/auth/login', method: 'post', propertyName: 'token' },
logout: false,
user: { url: '/auth/user', method: 'get', propertyName: 'user' },
},
}
},
redirect: {
login: '/login',
logout: '/',
callback: '/login',
home: '/admin/products',
},
},
// Build Configuration (https://go.nuxtjs.dev/config-build)
build: {
// babel: {
// compact: true,
// },
},
router: {
extendRoutes(routes, resolve) {
routes.push(
{
name: 'product-edit',
path: '/admin/products/edit/:id',
component: 'pages/admin/products/add.vue',
},
{
name: 'product-image-upload',
path: '/admin/products/product-image-upload/:id',
component: 'pages/admin/products/product-image-upload.vue',
},
{
name: 'gallery-image-upload',
path: '/admin/gallery-image-upload',
component: 'pages/admin/gallery-image-upload.vue',
},
);
}
},
env: {
baseUrl: `${process.env.BASE_URL}`,
imagePath: `${process.env.BASE_URL}:${process.env.API_PORT}/uploads`,
},
publicRuntimeConfig: {
baseUrl: `${process.env.BASE_URL}`,
imagePath: `${process.env.BASE_URL}:${process.env.API_PORT}/uploads`,
},
loading: '~/components/LoadingBar.vue',
i18n: {
locales: [
{ code: 'en', iso: 'en-US', file: 'en.js' },
{ code: 'hu', iso: 'hu-HU', file: 'hu.js' },
{ code: 'de', iso: 'de-DE', file: 'de.js' },
],
defaultLocale: 'en',
lazy: true,
langDir: '/i18n/',
parsePages: false,
vueI18n: {
fallbackLocale: 'en',
},
detectBrowserLanguage: {
useCookie: true,
cookieKey: 'i18n_redirected',
},
seo: false,
vueI18nLoader: true,
strategy: 'no_prefix',
},
lazySizes: {
extendAssetUrls: {
img: 'data-src',
source: 'data-srcset',
// Component with custom props
AppImage: ['source-md-url', 'image-url'],
},
},
optimizedImages: {
inlineImageLimit: 1000,
handleImages: ['jpeg', 'png', 'svg', 'webp', 'gif'],
optimizeImages: false,
optimizeImagesInDev: false,
defaultImageLoader: 'img-loader',
mozjpeg: {
quality: 80,
},
optipng: {
optimizationLevel: 3,
},
pngquant: false,
gifsicle: {
interlaced: true,
optimizationLevel: 3,
},
svgo: {
// enable/disable svgo plugins here
},
webp: {
preset: 'default',
quality: 75,
},
},
};
my docker-compose.yml
version: '3'
services:
server:
build:
context: ./server
env_file: .env
expose:
- $SERVER_PORT
ports:
- $SERVER_PORT:$SERVER_PORT
volumes:
- ./server:/usr/app
- /usr/app/node_modules
client:
build:
context: ./client
env_file: .env
environment:
NUXT_HOST: 0.0.0.0
NUXT_PORT: $CLIENT_PORT
API_HOST: 0.0.0.0
API_PORT: $SERVER_PORT
BASE_URL: $BASE_URL
volumes:
- ./client:/usr/app
- /usr/app/node_modules
expose:
- $CLIENT_PORT
ports:
- $CLIENT_PORT:$CLIENT_PORT
Update: if I start my nuxt project without Docker then everything works fine but this is not a solution for me :D
I have solved my question. I had to use nginx proxy as a container and some nuxt config.
// https://axios.nuxtjs.org/options/
privateRuntimeConfig: {
axios: {
baseURL: 'http://nginx/api' // name of the docker proxy
}
},

Resources