serialize-javascript icon indicating copy to clipboard operation
serialize-javascript copied to clipboard

Can't used in browser?

Open cx690 opened this issue 3 years ago • 3 comments

I want to use serialize-javascript in vite project. There are two problem,At first buffer is undefined,I install buffer,and then there is an error at randombytes,the error code is here:

//randombytes/browser.js
var crypto = global.crypto || global.msCrypto

if (crypto && crypto.getRandomValues) {
  module.exports = randomBytes
} else {
  module.exports = oldBrowser
}
.........

In browser,global is undefined! I try to change it as this:

const globalThis = typeof global === 'object' ? global : window;

var crypto = globalThis.crypto || globalThis.msCrypto

if (crypto && crypto.getRandomValues) {
  module.exports = randomBytes
} else {
  module.exports = oldBrowser
}

And then,serialize-javascript wrok!

cx690 avatar Nov 25 '21 09:11 cx690

I want to use serialize-javascript in vite project. There are two problem,At first buffer is undefined,I install buffer,and then there is an error at randombytes,the error code is here:

//randombytes/browser.js
var crypto = global.crypto || global.msCrypto

if (crypto && crypto.getRandomValues) {
  module.exports = randomBytes
} else {
  module.exports = oldBrowser
}
.........

In browser,global is undefined! I try to change it as this:

const globalThis = typeof global === 'object' ? global : window;

var crypto = globalThis.crypto || globalThis.msCrypto

if (crypto && crypto.getRandomValues) {
  module.exports = randomBytes
} else {
  module.exports = oldBrowser
}

And then,serialize-javascript wrok!

Finally, how did you solve it? I also have this problem at present

pk111and222 avatar Dec 24 '21 09:12 pk111and222

If buffer is undefined,you can install it. And then set this before your project!

window.global = { crypto:window.crypto };

cx690 avatar Dec 24 '21 09:12 cx690

I am also getting this issue when using Vite in a react project, but the above suggestions don't seem to help. Any other pointers on what this might be?

NoHara42 avatar Aug 26 '22 13:08 NoHara42