js-sha3 icon indicating copy to clipboard operation
js-sha3 copied to clipboard

Sveltekit + Vite unable to import function

Open Seancheey opened this issue 2 years ago • 3 comments

Environment

Sveltekit + Vite + NPM

Attempt 1

I tried to import with

import { sha3_512 } from "js-sha3";

but npm run build gives me an error message:

import { sha3_512 } from "js-sha3";
         ^^^^^^^^
SyntaxError: Named export 'sha3_512' not found. The requested module 'js-sha3' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from 'js-sha3';
const { sha3_512 } = pkg;

Attempt 2

However, when I switch to

import pkg from 'js-sha3';
const { sha3_512 } = pkg;

I found this runtime error:

...
Runtime.UnhandledPromiseRejection","errorMessage":"TypeError: sha3_512 is not a function","reason":{"errorType":"TypeError","errorMessage":"sha3_512 is not a function","stack":["TypeError: sha3_512 is not a function","
...

My Guess

I doubt the sha3_512 function is tree-shaked by vite compiler, but I'm not sure why.

Possible fix

  1. Try to make the package a non-CommonJS module by setting "type": "module" in package.json?
  2. Make sure to export the sha3_512 function in a way that vite build won't tree-shake the function?

Seancheey avatar Oct 26 '23 18:10 Seancheey

I tried this

import pkg from 'js-sha3';
const { sha3_512 } = pkg;

it works

Can you give an example project?

emn178 avatar Oct 27 '23 01:10 emn178

I tried this

import pkg from 'js-sha3';
const { sha3_512 } = pkg;

it works

Can you give an example project?

Thanks for quick response, yes,

vite is working fine for that method, but vite build then executing production package will raise an error.

Seancheey avatar Oct 27 '23 01:10 Seancheey

I use npm run build and got no error.

emn178 avatar Oct 27 '23 01:10 emn178