WalletConnect fails to get bundled with vite - reactjs

I have a vite project that uses #walletconnect/client. Everything works fine with
npm run dev
but during build (npm run build) I get these errors
error during build:
Error: 'removeHexPrefix' is not exported by node_modules/#walletconnect/encoding/dist/cjs/index.js, imported by node_modules/#walletconnect/utils/dist/esm/ethereum.js
I have tried a few vite configurations from github
1.
optimizeDeps: {
include: ['#walletconnect/*']
},
optimizeDeps: {
exclude: ['#walletconnect/*']
},
3
build: {
commonjsOptions: {exclude: ['#walletconnect*'], include: []},
},
I do not know anything else to do, but if you have come across this issue or something similar. Please let me know how you solved yours.
Thank you.

Had the same issue (I highly suggest you to check it out). Fixed with this config:
import { defineConfig } from "vite";
import { svelte } from "#sveltejs/vite-plugin-svelte";
import { NodeGlobalsPolyfillPlugin } from "#esbuild-plugins/node-globals-polyfill";
import inject from "#rollup/plugin-inject";
import nodePolyfills from "rollup-plugin-polyfill-node";
// https://vitejs.dev/config/
export default defineConfig({
base: "./",
// Node.js global to browser globalThis
define: {
global: "globalThis",
},
plugins: [
svelte(),
inject({
util: "util/",
}),
],
build: {
rollupOptions: {
plugins: [nodePolyfills()],
},
commonjsOptions: {
transformMixedEsModules: true,
},
},
optimizeDeps: {
esbuildOptions: {
// Node.js global to browser globalThis
define: {
global: "globalThis",
},
// Enable esbuild polyfill plugins
plugins: [
NodeGlobalsPolyfillPlugin({
buffer: true,
}),
],same issue
},
},
});```

Related

Vitest config doesn't detect jsdom environment

I'm in a Vite/React/TypeScript application and I'm configuring my first test with Vitest.
When I run my Button test (yarn vitest), I get this error:
packages/frontend/src/components/Generic/Button/Button.test.tsx > Button > should render the button
ReferenceError: document is not defined
I understand that Vitest does not work with JSDom. I have tried several things:
KO: Specifying in the vite.config.ts file to use JSDom
OK: Adding a vitest.config.ts file specifying to use JSDom
OK: Adding an annotation (#vitest-environment jsdom) at the top of the test file
I would prefere use the first option (use vite.config.ts) to share only one configuration. Is it possible ?
Note 1 : JSdom i already installed has "devDependencies".
Note 2 : to use vitest.config.ts i should update the script in package.json like that :
"test": "vitest --config ./packages/frontend/vitest.config.ts"
Here are my files:
// vite.config.ts
import { defineConfig } from 'vite'
import react from '#vitejs/plugin-react'
import viteTsConfigPaths from 'vite-tsconfig-paths'
import tailwindcss from 'tailwindcss'
export default defineConfig({
server: {
port: 4200,
host: 'localhost',
},
rollupOption: {
external: ['#internals/components/index']
},
define: {
global: {},
},
plugins: [
react(),
tailwindcss(),
viteTsConfigPaths({
root: '../../',
}),
],
resolve: {
alias: {
// runtimeConfig is a special alias that is used to import the correct config file
'./runtimeConfig': './runtimeConfig.browser',
// public alias
'#publics': `${__dirname}/public`,
// only internals (private) aliases are allowed here
'#internals/components': `${__dirname}/src/components`,
'#internals/features': `${__dirname}/src/features`,
'#internals/hooks': `${__dirname}/src/hooks`,
'#internals/models': `${__dirname}/src/models`,
'#internals/utils': `${__dirname}/src/utils`,
'#internals/types': `${__dirname}/src/types`,
'#internals/styles': `${__dirname}/src/styles`,
'#internals/assets': `${__dirname}/src/assets`,
'#internals/store': `${__dirname}/src/store`,
'#internals/config': `${__dirname}/src/config`,
'#internals/services': `${__dirname}/src/services`,
},
},
test: {
globals: true,
cache: {
dir: '../../node_modules/.vitest',
},
environment: 'jsdom',
include: ['*.tsx', '*.ts', '*.jsx', '*.js'],
},
})
I tried to add a like this vitest.config.ts :
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
include: ['*.ts', '*.tsx'], // FIXME
environment: 'jsdom',
},
})

Configuring Vite with styled-jsx

I want to be able to add classes through styled-jsx which can be nested and have tailwind directives(#apply screen etc.). Right now it's working on imported css files.
Here's my Vite config:
import { defineConfig } from "vite";
import react from "#vitejs/plugin-react";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
react({
babel: {
parserOpts: {
plugins: [
"styled-jsx/babel",
// {
// plugins: ["styled-jsx-plugin-postcss"],
// },
],
},
},
}),
],
});
As you see plugins: ["styled-jsx-plugin-postcss"] is commented, because it results in an error, but it's essential to use postcss settings.
If somebody interested, here's the postcss.config.cjs(for non Vite it's .js):
module.exports = {
plugins: {
'tailwindcss/nesting': 'postcss-nesting',
'postcss-preset-env': {
stage: 1
},
tailwindcss: {},
autoprefixer: {},
}
}
Is there a way to configure it in Vite.js ( in Next.js it's trivial, so if someone wants to suggest this idea, just don't, it's about Vite!)

Cannot convert lodash library from CommonJS to ES in Vitejs

I am building a project using Vite + React + Antd.
My project has lodash library, when i build with vite build command then get an error like below:
Running on environment production
vite v2.9.9 building for production...
transforming (2741) node_modules\.pnpm\lodash#4.17.21\node_modules\lodash\isLength.jsUnexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:
(commonjs) load "\u0000cross-fetch?commonjs-proxy"
error during build:
Error: Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:
(commonjs) load "\u0000cross-fetch?commonjs-proxy"
In my vite.config.js file, I added #rollup/plugin-commonjs,
import commonjs from '#rollup/plugin-commonjs';
import react from '#vitejs/plugin-react';
import { defineConfig, loadEnv } from 'vite';
export default ({ mode }) => {
const env = loadEnv(mode, 'env');
const htmlPlugin = () => {
return {
name: 'html-transform',
// Replace %VITE_X% env variables in index.html.
transformIndexHtml(html: string) {
return html.replace(/%(.*?)%/g, function match(_match, p1) {
return env[p1];
});
},
};
};
return defineConfig({
resolve: {
alias: [
{ find: /^~/, replacement: '' },
{ find: 'react/jsx-runtime', replacement: 'react/jsx-runtime.js' },
],
},
define: {
'process.env': process.env,
},
build: {
outDir: './build',
rollupOptions: {
plugins: [commonjs()],
},
commonjsOptions: {
exclude: [/./],
},
},
publicDir: './public',
css: {
preprocessorOptions: {
less: {
javascriptEnabled: true,
},
},
},
optimizeDeps: {
include: ['#ant-design/icons'],
},
plugins: [
htmlPlugin(),
react({
babel: {
plugins: [['#babel/plugin-transform-react-jsx', { runtime: 'automatic' }]],
},
}),
],
});
};
I tried to change lodash into lodash-es, but in my node_modules has a couple of libraries use it.
Please help me. Thank all

Getting an error when run "vite preview" (use Vite + React + Antd)

I am building a library with vite, react and ant design.
The build command vite build runs fine without warnings, but when I run vite preview command, then I give an error. I do not know why this is happening.
[![enter image description here][1]][1]
index.b71761d7.js:4879 TypeError: jsxDevRuntime.exports.jsxDEV is not a function
at Provider (index.b71761d7.js:31334:48)
at Ch (index.b71761d7.js:3752:8)
at ck (index.b71761d7.js:6267:12)
at bk (index.b71761d7.js:5797:12)
at ak (index.b71761d7.js:5790:5)
at Tj (index.b71761d7.js:5773:7)
at Lj (index.b71761d7.js:5541:26)
at Jg (index.b71761d7.js:5389:52)
at lk (index.b71761d7.js:6631:3)
at index.b71761d7.js:6719:7
Please help me, thank you very much!
This is my vite.config.js file
import { defineConfig, loadEnv } from 'vite';
import react from '#vitejs/plugin-react';
export default ({ mode }) => {
// Load app-level env vars to node-level env vars.
console.log('Running on environment ' + mode);
process.env = { ...process.env, ...loadEnv(mode, process.cwd()) };
return defineConfig({
plugins: [
react({
babel: {
plugins: [['#babel/plugin-transform-react-jsx', { runtime: 'automatic' }]],
},
}),
],
resolve: {
alias: [{ find: /^~/, replacement: '' }],
},
css: {
preprocessorOptions: {
less: {
modifyVars: {
// 'primary-color': '#282F7E',
'primary-color': '#F58220',
// 'text-color': '#282F7E',
'btn-border-radius-base': '6px',
'btn-border-radius-sm': '6px',
'control-border-radius': '6px',
'tag-border-radius': '6px',
dark: true,
compact: true,
},
javascriptEnabled: true,
},
},
},
optimizeDeps: {
include: ['#ant-design/icons'],
},
server: {
port: 3711,
},
preview: {
port: 8711,
},
build: {
chunkSizeWarningLimit: 1000,
outDir: 'build',
},
});
};
[1]: https://i.stack.imgur.com/gw1Wf.png

Build problem with React viteJS and was amplify

my question is quite simple to explain. I've initialized a React project with ViteJS and then added aws-amplify for the backend. I developed the project and everything works in my local environment running npm run dev. The problem is that I cannot build it.
You can see the error in the text below. Do you have any idea?
'request' is not exported by __vite-browser-external, imported by node_modules/#aws-sdk/credential-provider-imds/dist/es/remoteProvider/httpRequest.js
Error logs
In vite.config.js add:
resolve: {
alias: {
'./runtimeConfig': './runtimeConfig.browser',
},
}
in define field
Working config for React polyfilled for AWS SDK and Amplify
import { defineConfig } from "vite";
import react from "#vitejs/plugin-react";
import rollupNodePolyFill from "rollup-plugin-node-polyfills";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
optimizeDeps: {
esbuildOptions: {
// Node.js global to browser globalThis
define: {
global: "globalThis", //<-- AWS SDK
},
},
},
build: {
rollupOptions: {
plugins: [
// Enable rollup polyfills plugin
// used during production bundling
rollupNodePolyFill(),
],
},
},
resolve: {
alias: {
'./runtimeConfig': './runtimeConfig.browser', // <-- Fix from above
},
}
});
when using an array of aliases.
resolve: {
alias: [
{
find: '#', replacement: path.resolve(__dirname, './src'),
},
{
find: './runtimeConfig', replacement: './runtimeConfig.browser',
}
]
}
For the issue "'request' is not exported by __vite-browser-external", just install the http package (e.g 'npm i http')
It appears root cause of this type of issue is that aws-amplify JS lib is relying on Node specific features. There is a two part workaround:
To solve errors like 'xxxxx' is not exported by __vite-browser-external add additional alias for ./runtimeConfig to the vite.config.ts file. So it will look something like:
alias: {
"#": fileURLToPath(new URL("./src", import.meta.url)),
'./runtimeConfig': './runtimeConfig.browser',
},
To solve error like Uncaught ReferenceError: global is not defined, declare corresponding global variable in your topmost html file (index.html)
<script>
var global = global || window;
var Buffer = Buffer || [];
var process = process || {
env: { DEBUG: undefined },
version: []
};
</script>
There is github issue open for more than a year now: https://github.com/aws-amplify/amplify-js/issues/9639

Resources