LoginSignup
0
0

More than 1 year has passed since last update.

【Solana】Anchorを使用したWebアプリのビルドに失敗するとき (polyfill)

Last updated at Posted at 2022-03-21

動作確認環境

  • M1 Mac mini (macOS 12.3)
  • @project-serum/anchor : 0.23.0
  • webpack : 5.70.0
  • process : 0.11.10

事象

Solanaのクライアント側で@project-serum/anchorを使っていると、ビルドに失敗し以下のようなエラーに出くわすことがある。

Compiled with problems:

ERROR in ./node_modules/@project-serum/anchor/dist/browser/index.js 12:0-28

Module not found: Error: Can't resolve 'assert' in '<your project path>/node_modules/@project-serum/anchor/dist/browser'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
	- add a fallback 'resolve.fallback: { "assert": require.resolve("assert/") }'
	- install 'assert'
If you don't want to include a polyfill, you can use an empty module like this:
	resolve.fallback: { "assert": false }

また、エラー文で示されているようにassertパッケージをインストールしても正常にページが表示されない。

原因

@project-serum/anchorは内部でNode.jsのネイティブモジュールを使用しているが、webpack 5以降はNode.jsのpolyfillsが削除されたため、素直にビルドができなくなってしまった。
ちなみに、react-scriptなども内部でwebpackを使用しているため同じような事象が起こる。

対処方法

webpackのバージョンを4に落としてもいいのだが、それはそれで別の問題が発生する可能性あるため、ここではwebpackのプラグインを使って対処する。react-scriptを使用する場合のうまい対処方法は分からなかった。(ご存知の方いたら教えて下さい)

必要なパッケージをインストール

npm install assert process

webpack.config.js にプラグイン設定を追加

const webpack = require('webpack');

module.exports = {
  ...
  plugins: [
    new webpack.ProvidePlugin({
      process: 'process/browser',
      Buffer: ['buffer', 'Buffer'],
    }),
  ],
};

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0