I'm using VueJS v3 and trying to generate and display a BIP39 mnemonic using the bip39
library. However I am getting an error in the browser console:
Uncaught ReferenceError: global is not defined _stream_readable.js:48:20
js _stream_readable.js:48
__require chunk-PWNRNYY6.js:23
js readable-browser.js:1
__require chunk-PWNRNYY6.js:23
js index.js:3
__require chunk-PWNRNYY6.js:23
js index.js:3
__require chunk-PWNRNYY6.js:23
js browser.js:3
__require chunk-PWNRNYY6.js:23
js index.js:3
__require chunk-PWNRNYY6.js:23
<anonymous> bip39:1
js _stream_readable.js:48
__require chunk-PWNRNYY6.js:23
js readable-browser.js:1
__require chunk-PWNRNYY6.js:23
js index.js:3
__require chunk-PWNRNYY6.js:23
js index.js:3
__require chunk-PWNRNYY6.js:23
js browser.js:3
__require chunk-PWNRNYY6.js:23
js index.js:3
__require chunk-PWNRNYY6.js:23
<anonymous> bip39:1
InnerModuleEvaluation self-hosted:2393
InnerModuleEvaluation self-hosted:2393
InnerModuleEvaluation self-hosted:2393
InnerModuleEvaluation self-hosted:2393
evaluation self-hosted:2354
<script setup>
import { generateMnemonic } from "bip39";
import {ref} from "vue";
let mnemonic = ref(null);
mnemonic.value = generateMnemonic();
</script>
<template>
<div v-if="mnemonic !== null">
<h1>{{ mnemonic }}</h1>
</div>
</template>
Package.json
{
"name": "vue-app",
"version": "0.0.0",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview --port 5050"
},
"dependencies": {
"bip39": "^3.0.4",
"pinia": "^2.0.11",
"vue": "^3.2.31",
"vue-router": "^4.0.12"
},
"devDependencies": {
"@vitejs/plugin-vue": "^2.2.2",
"vite": "^2.8.4"
}
}
I can get this working outside of Vue in a plain .js
.
CodePudding user response:
Here's a live demo for a working solution:
https://codesandbox.io/s/bip39-vue-demo-5nlzy4
Got to say though, I didn't have an easy time trying out that module. I think its designed to be run server-side, and not in the browser like this. There may also be some security considerations to take account for if you're using this in production, but that's a separate issue.
Here's a working Vue component I built to demonstrate usage:
<template>
<div >
<div v-if="mnemonic">
<p><b>Result</b>: {{ mnemonic }} </p>
</div>
<div v-else>Loading....</div>
</div>
</template>
<script>
import { mnemonicToSeed } from 'bip39';
export default {
name: "GenerateMnemonic",
props: {
msg: String
},
data() {
return {
mnemonic: null,
};
},
mounted() {
mnemonicToSeed('basket actual')
.then(bytes => bytes.toString('hex'))
.then((result) => {
this.mnemonic = result;
});
},
};
</script>
<style scoped>
.hello {
max-width: 500px;
overflow-wrap: break-word;
margin: 0 auto;
text-align: left;
padding: 0 0.5rem;
border: 1px solid #2c3e50;
border-radius: 0.25rem;
}
</style>