I'm building a Nuxt-electron-prisma app and I kinda stuck here. when I use prisma normally as guided every thing is fine on dev but on build i get this error :
A javascript error occurred in the main process
Uncaught exception:
Error: can not find module : '.prisma/client'
I tried changing prisma provider output to ../resources/prisma/client
generator client {
provider = "prisma-client-js"
output = "../resources/prisma/client"
}
and in main.js of electron
const { PrismaClient } = require('../resources/prisma/client');
const prisma = new PrismaClient()
but I get error Cannot find module '_http_common' at webpackMissingModules in both dev and build ! which by others opinion is caused when using prisma on client-side but I only use it on background.js (main.js of the my boilerplate)
I'm using Nuxtron boilerplate for Nuxt-electron which is using yml file for electron-builder config file and in it I also added prisma to files property:
appId: com.example.app
productName: nuxt-electron-prisma
copyright: Copyright © 2021
nsis:
oneClick: false
perMachine: true
allowToChangeInstallationDirectory: true
directories:
output: dist
buildResources: resources
files:
- "resources/prisma/database.db"
- "node_modules/.prisma/**"
- "node_modules/#prisma/client/**"
- from: .
filter:
- package.json
- app
publish: null
and still get errors
in my win-unpacked/resources I have this only: win-unpacked\resources\app.asar.unpacked\node_modules\#prisma\engines
and of course my package.json
{
"private": true,
"name": "nuxt-electron-prisma",
"productName": "nuxt-electron-prisma",
"description": "",
"version": "1.0.0",
"author": "",
"main": "app/background.js",
"scripts": {
"dev": "nuxtron",
"build": "nuxtron build"
},
"dependencies": {
"electron-serve": "^1.0.0",
"electron-store": "^6.0.1",
"#prisma/client": "^3.0.2"
},
"devDependencies": {
"#mdi/font": "^6.1.95",
"#nuxtjs/axios": "^5.13.6",
"#nuxtjs/device": "^2.1.0",
"#nuxtjs/dotenv": "^1.4.1",
"#nuxtjs/vuetify": "1.12.1",
"core-js": "^3.15.1",
"electron": "^10.1.5",
"electron-builder": "^22.9.1",
"glob": "^7.1.7",
"noty": "^3.2.0-beta",
"nuxt": "^2.15.7",
"nuxtron": "^0.3.1",
"sass": "1.32.13",
"swiper": "^5.4.5",
"prisma": "^3.0.2",
"vue-awesome-swiper": "^4.1.1"
}
}
The solution provided by Mojtaba Barari works but it results in #prisma packages being present in both resources/app/node_modules and resources/node_modules.
There is a better way how to do it:
{
"build": {
"extraResources": [
{
"from": "node_modules/.prisma/client/",
"to": "app/node_modules/.prisma/client/"
}
],
}
}
In this case, the Prisma client files will be copied directly to resources/app/node_modules where other #prisma packages are already present and so you will save ~ 10 MB compared to the other solution.
EDIT:
My previous solution doesn't work if an application is packaged into an asar archive. You need to use files field instead:
{
"build": {
"files": [
{
"from": "node_modules/.prisma/client/",
"to": "node_modules/.prisma/client/"
}
],
}
}
This is a universal solution which works even if you don't use an asar archive.
Ok, I finally solved it!!
first of all no need to change client generator output direction!
//schema.prisma
datasource db {
provider = "sqlite"
url = "file:../resources/database.db"
}
generator client {
provider = "prisma-client-js"
// output = "../resources/prisma/client" !! no need for this!
}
then in electron-builder config add ./prisma , #prisma and database
// my config file was a .yml
extraResources:
- "resources/database.db"
- "node_modules/.prisma/**/*"
- "node_modules/#prisma/client/**/*"
// or in js
extraResources:[
"resources/database.db"
"node_modules/.prisma/**/*"
"node_modules/#prisma/client/**/*"
]
this solved `Error: cannot find module : '.prisma/client'
but this alone won't read DB in built exe file!
so in main.js where importing #prisma/client should change DB reading directory:
import { join } from 'path';
const isProd = process.env.NODE_ENV === 'production';
import { PrismaClient } from '#prisma/client';
const prisma = new PrismaClient({
datasources: {
db: {
url: `file:${isProd ? join(process.resourcesPath, 'resources/database.db') : join(__dirname, '../resources/database.db')}`,
},
},
})
with these configs I could fetch data from my sqlite DB
Related
I'm trying to use Synpress, but I fail to understand how to solve
TypeError: cy.acceptMetamaskAccess is not a function
Let me share the relevant code* (I mostly followed this tutorial https://medium.com/andamp/how-to-setup-synpress-for-wen3-dapp-frontend-test-automation-with-metamask-73396896684a)
*if something is missing, please let me know
package.json:
{
"devDependencies": {
"#testing-library/cypress": "^8.0.2",
"cypress": "^9.7.0"
},
"scripts": {
"cypress:open": "cypress open",
"test": "env-cmd -f .env npx synpress run -cf synpress.json --config supportFile='tests/support/index.js'",
"test:watch": "env-cmd -f .env npx synpress open -cf synpress.json"
},
"dependencies": {
"#synthetixio/synpress": "^1.2.0",
"env-cmd": "^10.1.0"
}
}
How I configured my synpress.json
{
"baseUrl": "https://dappify.com/",
"userAgent": "synpress",
"retries": { "runMode": 0, "openMode": 0 },
"integrationFolder": "tests/integration",
"screenshotsFolder": "screenshots",
"videosFolder": "videos",
"video": true,
"chromeWebSecurity": true,
"viewportWidth": 1366,
"viewportHeight": 850,
"component": {
"componentFolder": ".",
"testFiles": "**/*spec.{js,jsx,ts,tsx}"
},
"env": {
"coverage": false
},
"defaultCommandTimeout": 30000,
"pageLoadTimeout": 30000,
"requestTimeout": 30000,
"supportFile": "tests/support/index.js"
}
Simple test
describe('Test User Login', () => {
it('Connects with Metamask', () => {
cy.visit('https://dappify.com')
cy.contains('Sign').click();
cy.contains('Confirm').click();
cy.contains('Connect Wallet').click();
cy.contains('Metamask').click();
cy.switchToMetamaskWindow();
cy.acceptMetamaskAccess().should("be.true");
})
})
I don't understand why cy.acceptMetamaskAccess() is not a function, I can find it here: https://github.com/synthetixio/synpress/blob/master/support/index.d.ts
How can I use the functions listed in this index.d.ts file?
** Solution **
Answer by Fody was helpful! Let me summarise the steps needed:
inside support folder you need an index.js
inside index.js
import './commands'
import "#synthetixio/synpress/support";
If you want to add custom functions add this file to support too
inside commands.js:
import "#testing-library/cypress/add-commands";
// here go(es) your custom function(s)
It's a bit hard to untangle the Synpress structure. Usually with a plugin library you import a support component and that adds the library's custom commands to your test.
The article says
Run your tests with env-cmd -f .env npx synpress run -cf synpress.json --config supportFile='support/index.js'
which makes me think the last parameter is bringing in the custom commands.
If you already tried that, the following is the command definition, you can try adding it at the top of your spec.
Cypress.Commands.add('acceptMetamaskAccess', allAccounts => {
return cy.task('acceptMetamaskAccess', allAccounts);
})
Im creating an NFL football simulator in nodejs and am having trouble exporting one of my variables. As you can see in my get_teams.js i make many HTTP requests. I then process the responseArr and format the data. Where I am running into an issue is when I try and export the sorted_teams_array. you can find this code at the very bottom of get_teams.js.
I then try and import this array into tester.js and console log it. I will eventually use this file to inject a mongo database with the array, but for now am just trying to console log it and cannot get it to work. I am using the --experimental-modules in my npm scripts when I run npm run tester, and still nothing. Any help would be great! I am a noobie so please no hate!
get_teams.js
import axios from 'axios';
import Nfl_team from '../models/teamModel.js';
import Offensive_stats from '../models/offensiveStatsModel.js';
import Defensive_stats from '../models/defensiveStatsModel.js';
import Game_stats from '../models/gameStatsModel.js';
import colors from 'colors';
import dotenv from 'dotenv';
dotenv.config();
const teams = {};
function get_teams() {
axios.all([
axios.get(`https://api.sportsdata.io/api/nfl/fantasy/json/Standings/${process.env.SEASON}?key=${process.env.API_KEY}`),
// ... many more gets
])
.then(function (responseArr) {
responseArr[0].data.forEach(element => {
teams[element.Team] = new Nfl_team(element.Team, element.Name, element.Wins, element.Losses, element.Ties,
element.Percentage, element.DivisionWins, element.DivisionLosses, element.DivisionTies,
element.PointsFor, element.PointsAgainst)
});
// many more forEach blocks on responseArr[1, 2, 3...]
/* power rating algorithm logic
_____________________________________________ */
const teams_array = Object.entries(teams);
export const sorted_teams_array = teams_array.sort((a, b) => {
if (a[1].average_victory_margin > b[1].average_victory_margin) return -1;
if (a[1].average_victory_margin < b[1].average_victory_margin) return 1;
return 0;
})
console.log(sorted_teams_array);
teams_array.forEach(element => {
console.log(`average victory margin for ${element[0]} = ${element[1].average_victory_margin}`)
});
})
.catch(function (error) {
// handle error
console.log(error);
})
}
get_teams();
tester.js
import { sorted_teams_array } from './get_teams';
console.log(sorted_teams_array);
/// returns
(node:58769) ExperimentalWarning: The ESM module loader is experimental.
internal/modules/esm/resolve.js:61
let url = moduleWrapResolve(specifier, parentURL);
^
Error: Cannot find module /Users/jojovera/Documents/nflSIMULATION/teams/get_teams imported from /Users/jojovera/Documents/nflSIMULATION/teams/tester.js
at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:61:13)
at Loader.resolve (internal/modules/esm/loader.js:94:40)
at Loader.getModuleJob (internal/modules/esm/loader.js:240:28)
at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:42:40)
at link (internal/modules/esm/module_job.js:41:36) {
code: 'ERR_MODULE_NOT_FOUND'
}
package.json
{
"name": "optionsscript",
"version": "1.0.0",
"description": "",
"main": "app.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node --experimental-modules app.js",
"afc_west": "node --experimental-modules ../nflSIMULATION/teams/afc_west.js",
"get_teams": "node --experimental-modules ../nflSIMULATION/teams/get_teams.js",
"tester": "node --experimental-modules ../nflSIMULATION/teams/tester.js",
"get_offensive_stats": "node --experimental-modules ../nflSIMULATION/teams/get_offensive_stats.js",
"get_defensive_stats": "node --experimental-modules ../nflSIMULATION/teams/get_defensive_stats.js",
"get_victory_margin": "node --experimental-modules ../nflSIMULATION/teams/get_victory_margin.js",
"power_rank": "node --experimental-modules ../nflSIMULATION/teams/power_rank.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^0.21.0",
"cheerio": "^1.0.0-rc.5",
"colors": "^1.4.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"nodemon": "^2.0.6",
"stats-lite": "^2.2.0",
"terminal-kit": "^1.44.0",
"tofixed": "^1.0.0"
}
}
As addressed in the comments and chat, there were two issues: ESM isn't supported in Node 12, so an update to 15 fixed that. The other issue is that nothing was validly exported from get_teams: import and export are top-level keywords, and the export was taking place inside a .then. These minor changes allow the function to be imported and its result used in the tests:
export function get_teams() {
return axios.all([
/// rest of code
return sorted_teams_array;
})
.catch(function (error) {
// handle error
console.log(error);
})
}
Usage example:
import { get_teams } from './get_teams'
get_teams.then((teams) => {
teams.forEach(console.log)
})
I'm configuring simple project for testing using jest and babel. How do i make them work together ?
I have tried instructions mentioned here: https://jestjs.io/docs/en/getting-started but couldn't accomplish it.
abc.test.js
import {PI} from "./mathconsts";
describe("tests",()=>{
test('assert pi', () => {
expect(PI).toBe(3.14);
});
});
mathconsts.js
export const PI = 3.14;
package.json
{
"name": "simple-testing",
"version": "1.0.0",
"description": "Project to write simple tests",
"main": "index.js",
"scripts": {
"test": "jest"
},
"dependencies": {
"axios": "0.19.0",
"dotenv": "8.1.0"
},
"devDependencies": {
"#babel/core": "^7.6.4",
"#babel/preset-env": "^7.6.3",
"babel-jest": "^24.9.0",
"jest": "24.9.0",
"prettier": "1.18.2"
}
}
babel.config.js
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
node: 'current',
},
},
],
],
};
jest.config.js
module.exports = {
transformIgnorePatterns: [
"/node_modules/"
],
}
error found:
● Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
/Users/tests/abc.test.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { PI } from "./mathconsts";
^
SyntaxError: Unexpected token {
at ScriptTransformer._transformAndBuildScript (node_modules/#jest/transform/build/ScriptTransformer.js:537:17)
at ScriptTransformer.transform (node_modules/#jest/transform/build/ScriptTransformer.js:579:25)
How do i make it run ?
I am using Nuxt for my Vue project, It was working fine. I deleted my yarn and NPM cache due to other project issues. I re-installed the packages for my Nuxt app. The app is Universal and Uses express. Installation and Dev server is running, but when I try to visit http://localhost:3000/,
The error:
SyntaxError: Unexpected token export, shows up every time.
I know this is babel issue but I don't how to resolve this issue on Nuxt.
Nuxt Configuration:
const pkg = require('./package')
module.exports = {
mode: 'universal',
/*
** Headers of the page
*/
head: {
title: pkg.name,
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: pkg.description }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
},
/*
** Customize the progress-bar color
*/
loading: { color: '#fff' },
/*
** Global CSS
*/
css: [
'element-ui/lib/theme-chalk/index.css',
'#mdi/font/css/materialdesignicons.min.css'
],
/*
** Plugins to load before mounting the App
*/
plugins: [
'#/plugins/element-ui',
'~/plugins/vee-validate.js'
],
/*
** Nuxt.js modules
*/
modules: [
// Doc: https://github.com/nuxt-community/axios-module#usage
'#nuxtjs/axios',
'#nuxtjs/apollo'
],
apollo: {
tokenName: 'yourApolloTokenName', // optional, default: apollo-token
tokenExpires: 10, // optional, default: 7
includeNodeModules: true, // optional, default: false (this includes graphql-tag for node_modules folder)
authenticationType: 'Basic', // optional, default: 'Bearer'
// optional
errorHandler (error) {
console.log('%cError', 'background: red; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;', error.message)
},
// required
clientConfigs: {
default: {
// required
httpEndpoint: 'http://localhost:4000',
// optional
// See https://www.apollographql.com/docs/link/links/http.html#options
httpLinkOptions: {
credentials: 'same-origin'
},
// You can use `wss` for secure connection (recommended in production)
// Use `null` to disable subscriptions
wsEndpoint: null, // optional
// LocalStorage token
tokenName: 'apollo-token', // optional
// Enable Automatic Query persisting with Apollo Engine
persisting: false, // Optional
// Use websockets for everything (no HTTP)
// You need to pass a `wsEndpoint` for this to work
websocketsOnly: false // Optional
},
test: {
httpEndpoint: 'http://localhost:5000',
wsEndpoint: 'ws://localhost:5000',
tokenName: 'apollo-token'
},
// alternative: user path to config which returns exact same config options
}
},
/*
** Axios module configuration
*/
axios: {
// See https://github.com/nuxt-community/axios-module#options
},
/*
** Build configuration
*/
build: {
/*
** You can extend webpack config here
*/
extend(config, ctx) {
}
}
}
My package.json file
{
"name": "app",
"version": "1.0.0",
"description": "My exceptional Nuxt.js project",
"author": "Saima",
"private": true,
"scripts": {
"dev": "cross-env NODE_ENV=development nodemon server/index.js --watch server",
"build": "nuxt build",
"start": "cross-env NODE_ENV=production node server/index.js",
"generate": "nuxt generate"
},
"dependencies": {
"#mdi/font": "^3.3.92",
"#nuxtjs/apollo": "^4.0.0-rc2.3",
"#nuxtjs/axios": "^5.0.0",
"cross-env": "^5.2.0",
"element-ui": "^2.4.6",
"express": "^4.16.3",
"graphql-tag": "^2.10.1",
"less": "^3.9.0",
"less-loader": "^4.1.0",
"nuxt": "^2.0.0",
"vee-validate": "^2.1.5"
},
"devDependencies": {
"babel-preset-env": "^1.7.0",
"babel-register": "^6.26.0",
"nodemon": "^1.11.0"
}
}
Help would be appreciated.
I just checked your issue and it happens when you use element UI with Nuxt. Update your Nuxt configuration like this(Andrew Answer):
plugins: [
{src: '~/plugins/element-ui', ssr: false},
{src: '~/plugins/vee-validate.js', ssr: true},
],
This error can show up if you're importing an ES6 module which needs to be transpiled in order to load into the UI. In that case, this is fixed by adding the module into the transpile key of the build section of nuxt.config.js (at time of this post, the Nuxt transpile docs are a little confusing).
For instance, if you're trying to import a module called #stylelib then you'd want the following in your nuxt.config.js:
export default {
...
build: {
...
transpile: ['#stylelib']
}
}
I had the same issue and it was found in my nuxt.config.js file where i had placed some extra code with a ',' at the end of that code. The code in question was at the top of the file.
The code:
env: {
strapiBaseUri: process.env.API_URL || "http://localhost:1337"
},
My setup details are:
Nuxtjs (version as of March 20, 2020)
Apollo and Graphql
Strapi (backend)
For me (typescript Nuxt) it was using:
npm run start
instead of:
npm run dev
I'm building an app and all works fine while I'm in developer mode. Everythink works as it should. But when I package my app with electron-builder, app opens but it doesnt start express server and app doesnt work properly.
Here is my package.json code
{
"name": "artros",
"version": "1.0.0",
"description": "Artros",
"author": "MC3",
"license": "ISC",
"main": "start.js",
"scripts": {
"pack": "build --dir",
"dist": "build"
},
"build": {
"appId": "com.artros.app",
"productName": "Artros",
"win": {
"target": "portable",
"icon": "build/icon.ico"
},
"mac": {
"target": "dmg"
}
},
"dependencies": {
"body-parser": "^1.18.3",
"ejs": "^2.5.7",
"electron-pdf-window": "^1.0.12",
"express": "^4.16.2",
"multer": "^1.3.0",
"nodemailer": "^4.6.4",
"path": "^0.12.7"
},
"devDependencies": {
"electron": "^1.8.2"
}
}
and here is my start.js code
const cluster = require('cluster');
if (cluster.isMaster) {
require('./main.js'); // your electron main file
cluster.fork();
} else {
require('./app.js'); // your server code
}
and my main.js code
var electron = require('electron');
var browserWindow = electron.BrowserWindow;
var app = electron.app;
app.on('ready', function(){
var appWindow;
//appWindow
appWindow = new browserWindow({
width:1120,
height:620,
webPreferences: {
plugins: true
},
icon: __dirname + '/public/icon/icon.png'
});
appWindow.loadURL('file://' +__dirname + '/public/prva.html');
//appWindow.webContents.openDevTools();
});
// close app after all windows are closed
app.on('window-all-closed', () => {
app.quit()
})
If anybody has any idea what is the problem, please post it. Thanks
I had something similar happen to me. The challenge was that if you use fork() the application path changes. So I would recommend that you check __dirname in all of your files especially the ones in your forked process (e. g. app.js). I wouldn't be surprised if some of them don't make sense anymore.
I found the solution. The problem really was in my app.js code. At one detination I needed to add (path.join(__dirname, './path/to/file')). Guys thanks for your help.