Search code examples
javascriptruby-on-railsbabeljswebpacker

Babel loader failing to load typescript node_modules in a Rails - react app using webpacker


I'm failing to import a typescript library due to babel complaining about not having the correct loaders. I have a Rails backend with a React front-end, all in one application. Rails uses the webpacker gem to compile my React code into javascript packs. However, it's failing to load certain node_modules.

In my App.js, I attempt to import the packages:

import { configureChains, createConfig, WagmiConfig } from 'wagmi';

However, when I load my localhost, it fails.

chains.js:3 Uncaught Error: Module parse failed: Unexpected token (546:49)
File was processed with these loaders:
 * ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
|     if (!enabled) return;
|     if (!watch && !onBlock) return;
>     const publicClient_ = webSocketPublicClient ?? publicClient;
|     const unwatch = publicClient_.watchBlockNumber({
|       onBlockNumber: blockNumber => {
    at ./node_modules/wagmi/dist/index.js (chains.js:3:1)
    at __webpack_require__ (bootstrap:19:1)
    at ./app/javascript/components/App.jsx (index.scss:19:1)
    at __webpack_require__ (bootstrap:19:1)
    at ./app/javascript/packs/Index.jsx (SurveyContent.jsx:165:1)
    at __webpack_require__ (bootstrap:19:1)
    at bootstrap:83:1
    at bootstrap:83:1

Initially, I thought it was a babel problem with typescript, so I tried: bundle exec rails webpacker:install:typescript I've also tried npm install @babel/preset-typescript

Here's my config/webpacker.yml:

# Note: You must restart bin/webpack-dev-server for changes to take effect

default: &default
  source_path: app/javascript
  source_entry_path: packs
  public_root_path: public
  public_output_path: packs
  cache_path: tmp/cache/webpacker
  webpack_compile_output: true

  # Additional paths webpack should lookup modules
  # ['app/assets', 'engine/foo/app/assets']
  additional_paths: []

  # Reload manifest.json on all requests so we reload latest compiled packs
  cache_manifest: false

  # Extract and emit a css file
  extract_css: false

  static_assets_extensions:
    - .jpg
    - .jpeg
    - .png
    - .gif
    - .tiff
    - .ico
    - .svg
    - .eot
    - .otf
    - .ttf
    - .woff
    - .woff2

  extensions:
    - .tsx
    - .ts
    - .jsx
    - .mjs
    - .js
    - .sass
    - .scss
    - .css
    - .module.sass
    - .module.scss
    - .module.css
    - .png
    - .svg
    - .gif
    - .jpeg
    - .jpg

development:
  <<: *default
  compile: true

  # Reference: https://webpack.js.org/configuration/dev-server/
  dev_server:
    https: false
    host: localhost
    port: 3035
    public: localhost:3035
    hmr: false
    # Inline should be set to true if using HMR
    inline: true
    overlay: true
    compress: true
    disable_host_check: true
    use_local_ip: false
    quiet: false
    pretty: false
    headers:
      'Access-Control-Allow-Origin': '*'
    watch_options:
      ignored: '**/node_modules/**'


test:
  <<: *default
  compile: true

  # Compile test packs to a separate directory
  public_output_path: packs-test

production:
  <<: *default

  # Production depends on precompilation of packs prior to booting for performance.
  compile: false

  # Extract and emit a css file
  extract_css: true

  # Cache manifest.json for performance
  cache_manifest: true

And my babel.config.js

module.exports = function (api) {
  var validEnv = ['development', 'test', 'production']
  var currentEnv = api.env()
  var isDevelopmentEnv = api.env('development')
  var isProductionEnv = api.env('production')
  var isTestEnv = api.env('test')

  if (!validEnv.includes(currentEnv)) {
    throw new Error(
      'Please specify a valid `NODE_ENV` or ' +
      '`BABEL_ENV` environment variables. Valid values are "development", ' +
      '"test", and "production". Instead, received: ' +
      JSON.stringify(currentEnv) +
      '.'
    )
  }

  return {
    presets: [
      isTestEnv && [
        '@babel/preset-env',
        {
          targets: {
            node: 'current'
          },
          modules: 'commonjs'
        },
        '@babel/preset-react'
      ],
      (isProductionEnv || isDevelopmentEnv) && [
        '@babel/preset-env',
        {
          forceAllTransforms: true,
          useBuiltIns: 'entry',
          corejs: 3,
          modules: false,
          exclude: ['transform-typeof-symbol']
        }
      ],
      [
        '@babel/preset-react',
        {
          development: isDevelopmentEnv || isTestEnv,
          useBuiltIns: true
        }
      ],
      ['@babel/preset-typescript', { 'allExtensions': true, 'isTSX': true }]
    ].filter(Boolean),
    plugins: [
      'babel-plugin-macros',
      '@babel/plugin-syntax-dynamic-import',
      isTestEnv && 'babel-plugin-dynamic-import-node',
      '@babel/plugin-transform-destructuring',
      [
        '@babel/plugin-proposal-class-properties',
        {
          loose: true
        }
      ],
      [
        '@babel/plugin-proposal-object-rest-spread',
        {
          useBuiltIns: true
        }
      ],
      [
        '@babel/plugin-proposal-private-methods',
        {
          loose: true
        }
      ],
      [
        '@babel/plugin-proposal-private-property-in-object',
        {
          loose: true
        }
      ],
      [
        '@babel/plugin-transform-runtime',
        {
          helpers: false,
          regenerator: true,
          corejs: false
        }
      ],
      [
        '@babel/plugin-transform-regenerator',
        {
          async: false
        }
      ],
      isProductionEnv && [
        'babel-plugin-transform-react-remove-prop-types',
        {
          removeImport: true
        }
      ]
    ].filter(Boolean)
  }
}

I start my app via rails s --binding=127.0.0.1

Any suggestions for why this won't load? I assume it's something todo with my webpacker configuration, but I'm not even sure how to debug it.


Solution

  • It was an issue with webpacker. As it's retired, it's pointing to some old packages, and thus can't recognize the "??" operator.

    Followed this issue for a resolution by forcing a higher version of acorn. https://github.com/hotwired/turbo-rails/issues/336