emn178 / js-sha3

A simple SHA-3 / Keccak hash function for JavaScript supports UTF-8 encoding.
MIT License
345 stars 85 forks source link

Sveltekit + Vite unable to import function #36

Open Seancheey opened 8 months ago

Seancheey commented 8 months ago

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?
emn178 commented 8 months ago

I tried this

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

it works

Can you give an example project?

Seancheey commented 8 months ago

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.

emn178 commented 8 months ago

I use npm run build and got no error.