내맘대로 Study/블록체인

[클레이튼] caver.wallet.keyring.decrypt() 에러, Uncaught ReferenceError: Buffer is not defined

jinkwon.kim 2022. 5. 11. 23:47
728x90
반응형

목표

클레이튼 caver-js를 사용하면서 발생하는 Uncaught ReferenceError: Buffer is not defined 에러를 해결 합니다. 

발생 상황

caver-js를 통해서 keyring을 decrypt 할 때 발생 합니다.

caver.wallet.keyring.decrypt(this.auth.keystore, this.auth.password);

에러 정보

Uncaught (in promise) ReferenceError: Buffer is not defined
at decryptKey (keyringHelper.js:96:17)
at Function.decrypt (keyringFactory.js:423:25)
at testFunction (app.js:18:51)

원인

Webpack 5는 더 이상 Node.js의 핵심 모듈을 자동으로 폴리필하지 않습니다. 즉, 브라우저 등에서 실행되는 코드에서 사용하는 경우 npm에서 호환되는 모듈을 설치하고 직접 포함해야 합니다. 다음은 webpack 5 이전에 사용한 폴리필 목록입니다.

module.exports = {
  //...
  resolve: {
    fallback: {
      assert: require.resolve('assert'),
      buffer: require.resolve('buffer'),
      console: require.resolve('console-browserify'),
      constants: require.resolve('constants-browserify'),
      crypto: require.resolve('crypto-browserify'),
      domain: require.resolve('domain-browser'),
      events: require.resolve('events'),
      http: require.resolve('stream-http'),
      https: require.resolve('https-browserify'),
      os: require.resolve('os-browserify/browser'),
      path: require.resolve('path-browserify'),
      punycode: require.resolve('punycode'),
      process: require.resolve('process/browser'),
      querystring: require.resolve('querystring-es3'),
      stream: require.resolve('stream-browserify'),
      string_decoder: require.resolve('string_decoder'),
      sys: require.resolve('util'),
      timers: require.resolve('timers-browserify'),
      tty: require.resolve('tty-browserify'),
      url: require.resolve('url'),
      util: require.resolve('util'),
      vm: require.resolve('vm-browserify'),
      zlib: require.resolve('browserify-zlib'),
    },
  },
};

해결 방법 buffer module이 없어서 발생함

1. buffer 설치 

    $npm i -D buffer

2. webpack.config.js 에추가 

    1) Buffer: ['buffer', 'Buffer'] 추가

const webpack = require('webpack');

module.exports = {
    // ...

    plugins: [
        // Work around for Buffer is undefined:
        // https://github.com/webpack/changelog-v5/issues/10
        new webpack.ProvidePlugin({
            Buffer: ['buffer', 'Buffer'],
        }),
    ],

    2) resolve.fallback에 buffer추가

    resolve: {
        extensions: [ '.ts', '.js' ],
        fallback: {
            "buffer": require.resolve("buffer")
        }
    },

참조

https://stackoverflow.com/questions/68707553/uncaught-referenceerror-buffer-is-not-defined

 

Uncaught ReferenceError: Buffer is not defined

Our application kept showing the error in the title. The problem is very likely related to Webpack 5 polyfill and after going through a couple of solutions: Setting fallback + install with npm fa...

stackoverflow.com

 

728x90
반응형