jsencrypt icon indicating copy to clipboard operation
jsencrypt copied to clipboard

Support node.js ? ReferenceError: window is not defined

Open KingAmo opened this issue 2 years ago • 6 comments

  • node v16.19.1
  • jsencrypt 3.3.2
ReferenceError: window is not defined
    at Object.<anonymous> (/Users/x/x/node_modules/jsencrypt/bin/jsencrypt.js:18:4)
    at Module._compile (node:internal/modules/cjs/loader:1191:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1245:10)
    at Module.load (node:internal/modules/cjs/loader:1069:32)
    at Function.Module._load (node:internal/modules/cjs/loader:904:12)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:169:29)
    at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:530:24)
    at async loadESM (node:internal/process/esm_loader:91:5)

KingAmo avatar Jun 15 '23 03:06 KingAmo

降为3.2.1;在首行加上global.window = this试试

zhumenglonge avatar Jun 18 '23 00:06 zhumenglonge

这种线上打包 还要手动更改node_modules 包, 太不友好了

lanzhsh avatar Jul 03 '23 10:07 lanzhsh

import JSEncrypt from 'jsencrypt/lib/index.js'
const crypt = new JSEncrypt.default()

在node中使用可以这样用

aliothor avatar Jul 04 '23 10:07 aliothor

降为3.2.1;在首行加上global.window = this试试

加 global.window = this 可用

airwin avatar Aug 04 '23 09:08 airwin

今天也遇到了这个问题mock模拟数据时使用了jsencrypt加密出现的版本3.3.2 引入方式:

 import JSEncrypt from 'jsencrypt/bin/jsencrypt.min'
 let decrypt = new JSEncrypt()

解决方式:在jsencrypt.min.js文件中添加如下代码

const window=this

yantx avatar Nov 25 '23 01:11 yantx

Because import jsencrypt before global.window not create,it will result load to failed global.window,so you should use js the single-threaded,let global.window is created before to import jsencrypt, try

(async () => {
  global.window = this;
  const JSEncrypt = await import('jsencrypt');
  const jsencrypt = new JSEncrypt.default();
  jsencrypt.setPublicKey(publicKey); // u public key
  console.log(`token:\r\n${jsencrypt.encrypt(RSA_VALUE)}`);
})();

lancelot-song avatar Apr 29 '24 03:04 lancelot-song