Can't resolve 'http' in '/tmp/build_6c942c65/src' in Heroku: App works locally - node.js

My app which works locally cannot be pushed to heroku because of this error message:
Module not found: Error: Can't resolve 'http' in '/tmp/build_6c942c65/src'
Steps I have tried:
Downgrading react scripts to 4.0.2
Trying install http-browserify https-browserify and updating next.config.js to the below:
module.exports = {
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
config.resolve.alias.https = "https-browserify";
config.resolve.alias.http = "http-browserify";
return config;
},
};
Installing node-polyfill-webpack-plugin, creating a webpack.config.js and adding
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin');
module.exports = {
// Other rules...
plugins: [
new NodePolyfillPlugin()
]
};
Also
putting this in webpack.config.js
module.exports = {
target: "node",
}
Can anyone help.
App directory looks like this:
Can anyone help?
Thanks

Related

sveltekit environment variables are not working with turborepo and vercel deployment

Hi guys I have the following turborepo configuration
{
"$schema": "https://turbo.build/schema.json",
"pipeline": {
"build": {
"dependsOn": ["^build"],
"outputs": [".svelte-kit/**", ".vercel/**"],
"env": ["PUBLIC_SUPABASE_URL", "PUBLIC_SUPABASE_ANON_KEY"]
},
"lint": {},
"dev": {
"cache": false,
"persistent": true
}
}
}
It's a simple project with 2 sveltekit websites, admin and client, both websites have a supabase instance and the client is defined like this
import { createClient } from '#supabase/auth-helpers-sveltekit';
import { PUBLIC_SUPABASE_ANON_KEY, PUBLIC_SUPABASE_URL } from '$env/static/public';
export const client = createClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY);
in development locally it works perfectly but in production it fails with a different error for each website, for admin the vite config is this
import { sveltekit } from '#sveltejs/kit/vite';
import type { UserConfig } from 'vite';
const config: UserConfig = {
plugins: [sveltekit()],
optimizeDeps: {
exclude: ['flowbite-svelte']
},
define: {
'process.env': process.env
}
};
export default config;
and the error is this:
admin:build: throw new Error('supabaseUrl is required.');
admin:build: ^
admin:build:
admin:build: Error: supabaseUrl is required.
admin:build: at new SupabaseClient (/vercel/path0/node_modules/.pnpm/#supabase+supabase-js#2.4.1/node_modules/#supabase/supabase-js/dist/main/SupabaseClient.js:55:19)
Which just means it is not seeing the variables
for client the vite config is this
import { sveltekit } from '#sveltejs/kit/vite';
/** #type {import('vite').UserConfig} */
const config = {
plugins: [sveltekit()]
};
export default config;
and the error in vercel is this:
client:build: "PUBLIC_SUPABASE_URL" is not exported by "$env/static/public", imported by "src/lib/db.ts".
client:build: file: /vercel/path0/apps/client/src/lib/db.ts:2:35
client:build: 1: import { createClient } from '#supabase/auth-helpers-sveltekit';
client:build: 2: import { PUBLIC_SUPABASE_ANON_KEY, PUBLIC_SUPABASE_URL } from '$env/static/public';
client:build: ^
client:build: 3: export const client = createClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY);
client:build: error during build:
client:build: RollupError: "PUBLIC_SUPABASE_URL" is not exported by "$env/static/public", imported by "src/lib/db.ts".
client:build: at error (file:///vercel/path0/node_modules/.pnpm/rollup#3.7.3/node_modules/rollup/dist/es/shared/rollup.js:2001:30)
in both cases the issue is that the environment variables are not being loaded in both I don't understand why, I made sure the variables are configured correctly on vercel

Migrating cypress test from old version to latest version throws error

I am trying to migrate my test from Cypress 8.7.0 version to Cypress 10.10.0 version. Installed the latest version and did the below settings, but getting below error.
Using below versions:
Cypress 10.10.0,
"#badeball/cypress-cucumber-preprocessor": "^11.4.0",
node v18.4.0,
#bahmutov/cypress-esbuild-preprocessor": "^2.1.5"
Expected to find a global registry (this usually means you are trying to define steps or hooks in support/e2e.js, which is not supported) (this might be a bug, please report at https://github.com/badeball/cypress-cucumber-preprocessor)
Because this error occurred during a before each hook we are skipping all of the remaining tests.
I have added the error handling in e2e.js file and support/index.js file but still could not resolve this issue. I have .env file which has the environment variable in my root location. Could someone please advise on this issue ?
//Detail error log:
Because this error occurred during a `before each` hook we are skipping all of the remaining tests.
at fail (tests?p=tests/cypress/e2e/login/loginBase.feature:964:15)
at assert (tests?p=tests/cypress/e2e/login/loginBase.feature:971:9)
at assertAndReturn (tests?p=tests/cypress/e2e/login/loginBase.feature:975:9)
at getRegistry (tests?
Cypress version : v10.10.0
//tests/cypress/e2e/login/login.feature
#regression
#login
Feature: Login to base url
Scenario: Login to base url
Given I go to base url
//step defintion:
tests/cypress/stepDefinitions/login.cy.js
import { Given, When, Then, Before, After, And } from "#badeball/cypress-cucumber-preprocessor";
When('I go to base url', () => {
cy.visit(Cypress.config().baseUrl);
})
// tests/cypress/support/index.js file
// Import commands.js using ES2015 syntax:
import './commands'
Cypress.on('uncaught:exception', (err, runnable) => {
// returning false here prevents Cypress from
// failing the test
return false
});
//tests/cypress/support/e2e.js
// Import commands.js using ES2015 syntax:
import './commands'
Cypress.on('uncaught:exception', (err, runnable) => {
// returning false here prevents Cypress from
// failing the test
return false
})
//.cypress-cucumber-preprocessorrc.json // add this file in project root location
{
"stepDefinitions": [
"[filepath].{js,ts}",
"tests/cypress/stepDefinitions/**/*.{js,ts}"
]
}
// cypress.config.js
const { defineConfig } = require('cypress')
const createBundler = require("#bahmutov/cypress-esbuild-preprocessor");
const addCucumberPreprocessorPlugin = require("#badeball/cypress-cucumber-preprocessor")
const createEsbuildPlugin = require("#badeball/cypress-cucumber-preprocessor/esbuild").createEsbuildPlugin;
const dotenvPlugin = require('cypress-dotenv');
async function setupNodeEvents(on, config) {
await addCucumberPreprocessorPlugin.addCucumberPreprocessorPlugin(on, config);
on(
"file:preprocessor",
createBundler({
plugins: [createEsbuildPlugin(config)],
})
);
//webpack config goes here if required
config = dotenvPlugin(config)
return config;
}
module.exports = defineConfig({
e2e: {
baseUrl: 'https://bookmain.co',
apiUrl: 'https://bookmain.co/api/books/',
specPattern: "tests/cypress/e2e/**/*.feature",
supportFile: false,
setupNodeEvents
},
component: {
devServer: {
framework: "next",
bundler: "webpack",
},
},
});
// package.json
"cypress-cucumber-preprocessor": {
"nonGlobalStepDefinitions": true,
"stepDefinitions": "tests/cypress/stepDefinitions/**/*.{js,ts}",
"cucumberJson": {
"generate": true,
"outputFolder": "tests/cypress/cucumber-json",
"filePrefix": "",
"fileSuffix": ".cucumber"
}
},
In cypress.config.js add the following:
const {dotenvPlugin} = require('cypress-dotenv');
module.exports = (on, config) => {
config = dotenvPlugin(config)
return config
}
This will resolve the issue.

Using crypto.randomInt() in React

I am trying to use crypto.randomInt() Nodejs API in a project bootstrapped with create-react-app that uses Webpack 5. I have tried multiple options like this so far:
// webpack.config.js
module.exports = {
resolve: {
fallback: { crypto: require.resolve('crypto-browserify') },
}
};
And then, npm i crypto-browserify as recommended by the error message.
// Returns Uncaught TypeError: randomInt is not a function
const { randomInt } = import('crypto');
console.log(randomInt(4));
From some threads, I tried:
// package.json
...
"browser": {
"crypto": false
}
...
Still, no luck. I tried import {randomInt} from 'crypto-browserify'. This didn't work either.
What should I do to make this work?

How do I integrate NewRelic into a Node Typescript Express server bundled with Webpack?

Frankly, I've tried it all. I'm not a total whiz with Webpack, however I seem to be getting along pretty well over the years with configuring new projects.
What I cannot seem to do now is set up the NewRelic service into an existing Node/Typescript/Express/Webpack application.
As it stands, my app gets nicely bundled to a single file in my /dist folder and runs quick and nimble. Seems like this 'node agent' put out by New Relic doesn't play well with Typescript imports.
Webpack Config
const path = require('path');
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');
const NodemonPlugin = require ('nodemon-webpack-plugin');
module.exports = (env = {}) => {
const config = {
entry: ['./src/app.ts'],
mode: env.development ? 'development' : 'production',
target: 'node',
devtool: env.development ? 'inline-source-map' : false,
resolve: {
extensions: ['.ts', '.js'],
modules: ['node_modules', 'src', 'package.json'],
},
module: {
rules: [
{
test: /\.ts$/,
use: ['ts-loader', 'eslint-loader'],
// exclude: /node_modules/,
},
],
},
plugins: [],
externals: [ 'newrelic', nodeExternals() ]
};
if (env.nodemon) {
config.watch = true;
config.plugins.push(new NodemonPlugin())
}
return config;
};
there exists a standard /project_root/.newrelic file
CircleCi picks up this project up and runs "build:ci" script from package.json ==> "webpack"
output is /dist/main.js
references
https://docs.newrelic.com/docs/agents/nodejs-agent/installation-configuration/install-nodejs-agent
https://docs.newrelic.com/docs/agents/nodejs-agent/installation-configuration/nodejs-agent-configuration
https://discuss.newrelic.com/t/node-agent-fails-with-webpack/24874
Your first line of the starting point of the app should be
import newrelic from 'newrelic';
Of course, run npm install newrelic --save first
Then, create a newrelic.js file on the root of the repo (outside of src).
Then you put in the details like:
'use strict'
exports.config = {
app_name: ['appName'],
license_key: '1234567890',
allow_all_headers: true,
attributes: {
exclude: [
'request.headers.cookie',
'request.headers.authorization',
'request.headers.proxyAuthorization',
'request.headers.setCookie*',
'request.headers.x*',
'response.headers.cookie',
'response.headers.authorization',
'response.headers.proxyAuthorization',
'response.headers.setCookie*',
'response.headers.x*'
]
}
}

Bundle error using webpack for Electron application `Cannot resolve module 'electron'`

I am trying to create an Electron application with React. I use Webpack to compile the React JSX syntax, but when I try to compile with webpack command, I got this error:
ERROR in ./app.jsx
Module not found: Error: Cannot resolve module 'electron' in /Users/masterT/Downloads/gist
# ./app.jsx 6:18-37
Here is the application code.
I am doing something wrong?
A very simple solution :
const remote = window.require('electron').remote;
webpack will ignore this require
Webpack tries to resolve electron module with the installed node_modules. But the electron module is resolved in Electron itself at runtime. So, you have to exclude particular module from webpack bundling like this:
webpack.config.js:
module.exports = {
entry: './app.jsx',
output: {
path: './built',
filename: 'app.js'
},
target: 'atom',
module: {
loaders: [
{
loader: 'babel',
test: /\.jsx$/,
query: {
presets: ['es2015', 'react']
}
}
]
},
externals: [
(function () {
var IGNORES = [
'electron'
];
return function (context, request, callback) {
if (IGNORES.indexOf(request) >= 0) {
return callback(null, "require('" + request + "')");
}
return callback();
};
})()
]
};
You can set target: 'electron' in your webpack config and then you don't have to exclude electron in externals.
From webpack documentation:
"electron" Compile for usage in Electron – supports require-ing Electron-specific modules.
I tried most of the above examples, but none of them seemed to work for me.
I then installed Electron using npm and then used yarn build
It worked and I got my production build.
npm i electron
Also, webpack.config.js:
const nodeExternals = require('webpack-node-externals')
module.exports = {
...
externals: [ nodeExternals(), 'react', 'electron' ],
...
}
Your package.json has 'electron-prebuilt' but you require 'electron' in your code. Have you tried require-ing 'electron-prebuild'?

Resources