【Ruby on Rails】rails6とwebpack5で発生したエラーを解決するまでの長い道のり

Ruby on Rails

バージョン
rails v6.0.3
ruby v2.7.5
webpacker v4.3.0
webpack v5.67.0

package.json

エラーのはじまり

rails newでプロジェクトを作成して、最初の動作確認でエラーは起こりました。

Webpacker::Manifest::MissingEntryError

ターミナル上でのエラー表示
1〜4番の解決策を提示してくれています。

ActionView::Template::Error (Webpacker can't find application in /Users/省略/public/packs/manifest.json. Possible causes:
1. You want to set webpacker.yml value of compile to true for your environment
   unless you are using the `webpack -w` or the webpack-dev-server.
2. webpack has not yet re-run to reflect updates.
3. You have misconfigured Webpacker's config/webpacker.yml file.
4. Your webpack configuration is not creating a manifest.
Your manifest contains:
{
}
):
     6:     = csrf_meta_tags
     7:     = csp_meta_tag
     8:     = stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload'
     9:     = javascript_pack_tag 'application', 'data-turbolinks-track': 'reload'
    10:   %body
    11:     %header
    12:       %nav.navbar.navbar-expand-sm.navbar-light.bg-light
  
app/views/layouts/application.html.haml:9

エラー原因

4番のmanifest.jsonが存在しないせいです。

下記のコマンドを実行して、コンパイルすると解決します。参考

$ bin/rails webpacker:compile

私の場合、コマンドを実行すると別のエラーが発生しました。

[webpack-cli] Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.

次なるエラーが発生、、、。

$ bin/rails webpacker:compile
                                                                                                                                      
Compiling...
Compilation failed:
[webpack-cli] Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
 - configuration.node should be one of these:
   false | object { __dirname?, __filename?, global? }
   -> Include polyfills or mocks for various node stuff.
   Details:
    * configuration.node has an unknown property 'dgram'. These properties are valid:
      object { __dirname?, __filename?, global? }
      -> Options object for node compatibility features.
    * configuration.node has an unknown property 'fs'. These properties are valid:
      object { __dirname?, __filename?, global? }
      -> Options object for node compatibility features.
    * configuration.node has an unknown property 'net'. These properties are valid:
      object { __dirname?, __filename?, global? }
      -> Options object for node compatibility features.
    * configuration.node has an unknown property 'tls'. These properties are valid:
      object { __dirname?, __filename?, global? }
      -> Options object for node compatibility features.
    * configuration.node has an unknown property 'child_process'. These properties are valid:
      object { __dirname?, __filename?, global? }
      -> Options object for node compatibility features.

エラーを見ると、「dgramfsnettlschild_processが不明なプロパティです」と書いてあります。

試しにwebpack.config.jsの設定を確認してみます。
ターミナルで下記のコマンドを実行します。

確認方法

$ node
> wp = require('@rails/webpacker')
> new wp.Environment
出力結果

Base {
  loaders: ConfigList(7) [
    { key: 'file', value: [Object] },
    { key: 'css', value: [Object] },
    { key: 'sass', value: [Object] },
    { key: 'moduleCss', value: [Object] },
    { key: 'moduleSass', value: [Object] },
    { key: 'nodeModules', value: [Object] },
    { key: 'babel', value: [Object] }
  ],
  plugins: ConfigList(4) [
    { key: 'Environment', value: [EnvironmentPlugin] },
    { key: 'CaseSensitivePaths', value: [CaseSensitivePathsPlugin] },
    { key: 'MiniCssExtract', value: [MiniCssExtractPlugin] },
    { key: 'Manifest', value: [WebpackAssetsManifest] }
  ],
  config: ConfigObject {
    mode: 'production',
    output: {
      filename: 'js/[name]-[contenthash].js',
      chunkFilename: 'js/[name]-[contenthash].chunk.js',
      hotUpdateChunkFilename: 'js/[id]-[hash].hot-update.js',
      path: '/Users/省略/public/packs',
      publicPath: '/packs/'
    },
    resolve: { extensions: [Array], plugins: [Array] },
    resolveLoader: { modules: [Array], plugins: [Array] },
    node: {        これ!!!
      dgram: 'empty',
      fs: 'empty',
      net: 'empty',
      tls: 'empty',
      child_process: 'empty'
    }
  },
  entry: ConfigObject {
    application: '/Users/省略/app/javascript/packs/application.js'
  },
  resolvedModules: ConfigList(2) [
    {
      key: 'source',
      value: '/Users/省略/app/javascript'
    },
    { key: 'node_modules', value: 'node_modules' }

エラーと同じプロパティ名がありますね。

どうやら webpack5からnodeの仕様が変わって、global__filename__dirnameしか設定できなったようです。

Node | webpack
webpack is a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packagi...

これらを削除すれば、問題なく動くはず、、、。

削除方法

こちらを参考にしました。

config/webpack/environment.jsに以下のコードを追加してください。

const { environment } = require('@rails/webpacker')

// 追加 
// ここから
const customConfig = {
  resolve: {
    fallback: {
      dgram: false,
      fs: false,
      net: false,
      tls: false,
      child_process: false
    }
  }
};

environment.config.delete('node.dgram')
environment.config.delete('node.fs')
environment.config.delete('node.net')
environment.config.delete('node.tls')
environment.config.delete('node.child_process')

environment.config.merge(customConfig);
// ここまで

module.exports = environment

詳しい動作は勉強不足で把握できていません。
webpackのresolve.fallbackオプションを使用しているみたいです。

上記のコードを実行するために、webpackのloaderをインストールします。
インストールしないとbin/rails webpacker:compile実行時にエラーを吐きます。

babel-loader
$ npm install -D babel-loader @babel/core @babel/preset-env webpack

style-loader
$ npm install --save-dev style-loader

css-loader
$ npm install --save-dev css-loader

sass-loader
$ npm install sass-loader sass webpack --save-dev

おそらく4つでいけるはず。
必要なloaderはエラーに表示されるので、必要に応じてインストールしてください。

追加後にbin/rails webpacker:compileを実行する。

$ bin/rails webpacker:compile

またまた別のエラーが、、、、

Error: error:0308010C:digital envelope routines::unsupported

node.js v17系で起きるエラーみたいです。

公式のバグ報告で解決方法がありました。

ターミナルで下記のコマンドを実行すると解決します。

$ export NODE_OPTIONS=--openssl-legacy-provider

再度、bin/rails webpacker:compileを実行

いけました。

まとめ

長い道のりでした、、、、。

webpackはエラーが多いので、誰かの参考になれば幸いです。

コメント

タイトルとURLをコピーしました