Webpacker: Uncaught TypeError: __webpack_require__(...) is not a function - error on fresh app

Created on 29 May 2019  ·  46Comments  ·  Source: rails/webpacker

Repro Steps

Create fresh rails app

rails _6.0.0.rc1_ new hello

Add a controller and a view, then load it.

Expected Result

JavaScript loads correctly.

Actual Result

Uncaught TypeError: __webpack_require__(...) is not a function
    at Module../node_modules/webpack/buildin/harmony-module.js (harmony-module.js:33)
    at __webpack_require__ (bootstrap:19)
    at Module../node_modules/@rails/ujs/lib/assets/compiled/rails-ujs.js (rails-ujs.js:822)
    at __webpack_require__ (bootstrap:19)
    at Object../app/javascript/packs/application.js (application.js:6)
    at __webpack_require__ (bootstrap:19)
    at bootstrap:83
    at bootstrap:83

May be related to recent release / #2031

babecoreJs bug

Most helpful comment

For others experiencing this issue, you can remove both the corejs: 3 lines from babel.config.js and run:

rails tmp:clear

Restart your web server and it should work.

All 46 comments

For others experiencing this issue, you can remove both the corejs: 3 lines from babel.config.js and run:

rails tmp:clear

Restart your web server and it should work.

Can you post your package.json & babel.config.js?

I have the same error on a fresh app. ~In addition to your solution I also had to change the corejs version in the babel.config.js to version 2 (two occurences) to get this to work.~

Update: I actually removed both corejs occurences. Only then it worked for me.

package.json

{
  "name": "hello",
  "private": true,
  "dependencies": {
    "@rails/actioncable": "^6.0.0-alpha",
    "@rails/activestorage": "^6.0.0-alpha",
    "@rails/ujs": "^6.0.0-alpha",
    "@rails/webpacker": "^4.0.4",
    "turbolinks": "^5.2.0"
  },
  "version": "0.1.0",
  "devDependencies": {
    "webpack-dev-server": "^3.4.1"
  }
}

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 && [
        require('@babel/preset-env').default,
        {
          targets: {
            node: 'current'
          }
        }
      ],
      (isProductionEnv || isDevelopmentEnv) && [
        require('@babel/preset-env').default,
        {
          forceAllTransforms: true,
          useBuiltIns: 'entry',
          corejs: 3,
          modules: false,
          exclude: ['transform-typeof-symbol']
        }
      ]
    ].filter(Boolean),
    plugins: [
      require('babel-plugin-macros'),
      require('@babel/plugin-syntax-dynamic-import').default,
      isTestEnv && require('babel-plugin-dynamic-import-node'),
      require('@babel/plugin-transform-destructuring').default,
      [
        require('@babel/plugin-proposal-class-properties').default,
        {
          loose: true
        }
      ],
      [
        require('@babel/plugin-proposal-object-rest-spread').default,
        {
          useBuiltIns: true
        }
      ],
      [
        require('@babel/plugin-transform-runtime').default,
        {
          helpers: false,
          regenerator: true,
          corejs: 3
        }
      ],
      [
        require('@babel/plugin-transform-regenerator').default,
        {
          async: false
        }
      ]
    ].filter(Boolean)
  }
}

Same issue here, same package.json and babel.config.js

Tried to change the webpacker gem version as suggested above, no luck.

Was attempting to get Bootstrap installed, but have moved back to first installation to debug. Further information on my SO thread: https://stackoverflow.com/questions/56366873/cant-install-bootstrap-in-new-rails-6rc1-project-error-in-harmony-module-js

@wilpar @d-simon Did you run rails webpacker:install and overwrite all the files after downgrading Webpacker to 4.0.2?

Doing a completely new project with --skip-webpack-install and changing version before installing webpack. results in a few minutes.

yes, error persists.
steps

  1. rails new testapp --skip-bundle --skip-webpacker-install
  2. change webpacker version to 4.0.2 and run bundle and webpacker install
  3. add simple scaffold, change root to the index action

same error

running a mac, latest os, latest ruby 2.6.3

I have removed the corejs lines from babel.config.js and the error has gone away, but I am now receiving the deprecation warnings

Experiencing this error as well. Brand new 6.0.0.rc1 app on ruby 2.6.3. Downgrading the gem and reinstalling webpacker still resulted in errors.

dont forget to change the "@rails/webpacker": "^4.0.2" in your package.json and run yarn install again

Thanks @AmirolAhmad. I totally missed that.

fwiw, it works for me without changing package.json. You may need to run rake tmp:clear after downgrading the Webpacker gem.

Sorry the noise. It looks like downgrading isn't really needed. All downgrading does is effectively remove the corejs: 3 lines from babel.config.js, so you can do that by hand and run rails tmp:clear. Will update the solution above.

Here's the min difference between working and not working:

diff --git a/babel.config.js b/babel.config.js
index b8b230b..f930f3e 100644
--- a/babel.config.js
+++ b/babel.config.js
@@ -30,7 +30,6 @@ module.exports = function(api) {
         {
           forceAllTransforms: true,
           useBuiltIns: 'entry',
-          corejs: 3,
           modules: false,
           exclude: ['transform-typeof-symbol']
         }
@@ -57,8 +56,7 @@ module.exports = function(api) {
         require('@babel/plugin-transform-runtime').default,
         {
           helpers: false,
-          regenerator: true,
-          corejs: 3
+          regenerator: true
         }
       ],
       [

@ankane I see that you specify useBuiltIns: 'entry', but don't have core-js or regenerator-runtime prerequisites in your package.json. I tried to convey this requirement in the changelog.

Could you test the corejs: 3 config again with those packages installed?

Same issue here: clean Ruby 2.6.3, Rails 6.0.0.rc1 and new app with that error.

Think it's safe to say a lot people building a new Rails 6.0.0.rc1 app at the moment are in for some head scratching. Only found this issue and the fix (thanks @ankane !) by explicitly navigating here - Googling will send you on a bit of a goose chase.

I am unable to reproduce the issue in a fresh app. It would be immensely helpful if someone experiencing this issue could put the following in a https://gist.github.com/ :

Edit: found a way to reproduce. Looking into it...

This related issue has led me to a solution: https://github.com/babel/babel/issues/9903#issuecomment-491985234

I have been thinking about this issue today, and I think that the proper solution would be to transpile @babel/runtime's helpers using @babel/plugin-transform-runtime itself.
This is tricky, because we should avoid transpiling everything else except for polyfills, to avoid injecting references to themselves inside the helpers.

I have created a PR to fix this here (works with corejs: 3): https://github.com/rails/webpacker/pull/2110

Edit: You can hotfix by putting this in your environment.js file:

environment.loaders.get('nodeModules').exclude = /(?:@?babel(?:\/|\\{1,2}|-).+)|regenerator-runtime|core-js|webpack/;

OT: Remember when we moved from 4:3 TVs to 16:9? Webpacker feels the same.

released 4.0.5

Hey @jakeNiemiec and @gauravtiwari, thanks for the quick fix. I'm still seeing the same error with Webpacker 4.0.5 unfortunately. Maybe someone else in this thread can also try it?

(I reran the repro instructions above and confirmed webpacker 4.0.5 in Gemfile.lock and package.json)

Perhaps it is the same issue. I have seen similar messages in my setup here. I am trying to run the "Hello vuejs" on Rails 5.2.3, ruby 2.6.1 on a Mac machine. And I get similar messages. Thank you in advance for the assistance.

Oh I see, it might have to do with node_modules loader. Checking..

@ankane I don't think you need the corejs option there

 require('@babel/plugin-transform-runtime').default,
        {
          helpers: false,
          regenerator: true,
          corejs: 3
        }

since this should be handled by preset-env anyway. Unless I am missing something?

@ankane @meredoschi Can you tell me if putting: environment.loaders.delete('nodeModules'); in your config/webpack/environment.js file fixes it?

@jakeNiemiec yes, this fixes it for me

Initially, I got an error message. Then after doing:
yarn install --check-files
It worked.
Many thanks!

@gauravtiwari Reading the docs for @babel/plugin-transform-runtime(https://babeljs.io/docs/en/babel-plugin-transform-runtime#why), I am not sure that it is doing us any favors since we transpile all of node_modules.

Alternatively, we could play with the exclude option on babel-preset-env. It mentions @babel/plugin-transform-regenerator explicitly:

This option is useful for "blacklisting" a transform like @babel/plugin-transform-regenerator if you don't use generators and don't want to include regeneratorRuntime (when using useBuiltIns) or for using another plugin like fast-async instead of Babel's async-to-gen.

Edit: I missed the part at the top where it says "The transformation plugin is typically used only in development".

image

Babel is, by far, my weakest field; plus the docs don't all seem to be updated with the core-js@3 changes. The problem: we have a mystery package that is depended on by babel OR core-js, this package breaks ONLY at runtime not compile time.


If anyone still gets breakage, please post environment.js, package.json, babel.config.js and application.js to a https://gist.github.com

@JakeLaCombe environment.loaders.delete('nodeModules') fixes it for me.

fwiw, the previous hotfix (environment.loaders.nodeModules.exclude = /(?:@?babel(?:\/|\\{1,2}|-).+)|regenerator-runtime|core-js/;) does not.

@jakeNiemiec I ran a fresh project and I still run into the error.
Here's a gist of the requested files: https://gist.github.com/d-simon/faeda344a2c1a13b24c41e4eed041ac3

I just created a new rails 6.0.0.rc1 app a few hours ago which came with webpacker 4.0.4. Upgrating to webpacker 4.0.5 (https://github.com/rails/webpacker/pull/2110) fixed the issue. Thank you very much @jakeNiemiec

@d-simon Related PR that should fix your issue: https://github.com/rails/webpacker/pull/2111

Update: You can hotfix by putting this in your environment.js file (even better version):

environment.loaders.get('nodeModules').exclude = /(?:@?babel(?:\/|\\{1,2}|-).+)|regenerator-runtime|core-js|webpack/;

Hey @jakeNiemiec, getting a different error with that hotfix (and Webpacker 4.0.5):

Uncaught TypeError: Cannot set property 'Rails' of undefined
    at rails-ujs.js:22
    at rails-ujs.js:37
    at rails-ujs.js:38
    at Module.<anonymous> (rails-ujs.js:822)
    at Module../node_modules/@rails/ujs/lib/assets/compiled/rails-ujs.js (rails-ujs.js:822)
    at __webpack_require__ (bootstrap:19)
    at Object../app/javascript/packs/application.js (application.js:8)
    at __webpack_require__ (bootstrap:19)
    at bootstrap:83
    at bootstrap:83

Released 4.0.6, thanks @jakeNiemiec

BTW, I am wondering would it make sense to make nodeModules rule optional and let people declare deps that they want to compile with babel instead of us compiling everything by default. The idea earlier to keep the output consistent (ES5) but it seems it's breaking more things than helping.

Basically something along this line, so we declare packages that needs compiling (should be done by authors but if not)

environment.compileNodeModules(['es6-package', 'some-other-es6-package'])

fwiw, seeing the same error as reported in https://github.com/rails/webpacker/issues/2109#issuecomment-497510204 in 4.0.6

@ankane Sorry about that. I would say to disable corejs for runtime for now, will look into this properly and propose a fix.

 require('@babel/plugin-transform-runtime').default,
        {
          helpers: false,
          regenerator: true,
          corejs: false // or just remove this line (default is false)
        }

Can confirm: I'm getting the very same error as @ankane is getting with a fresh 4.0.6.

Thanks for looking into it and providing solution 👍🏻 I'm now off again to continue my exploration of Rails 6 now :)

Can confirm as well. Same error as @d-simon and @ankane with 4.0.6 (updated from a fresh 4.0.4).

No errors if I use corejs: false as @gauravtiwari suggested.

I started testing what @babel/plugin-transform-runtime was actually giving us. Pardon the sloppy writeup, skip to the bottom for a summary.

For the following, I simply import an empty class from another file:

These gave the same result. The same thing happens if I just require("@rails/ujs").start() or just require("turbolinks").start().


In this one, you can see that no polyfilling is occurring when corejs: false. Additionally the corejs: false output is identical to the output I get if @babel/plugin-transform-runtime is commented out altogether.

image

core-js
Specifying a number will rewrite the helpers that need polyfillable APIs to reference core-js instead.

It seems like the default babel helpers option is overridden by the default webpacker babel.config.js. Setting corejs: 3 will (seemingly) supersede helpers: false which inlines the corejs polyfill helpers.


TL;DR: Take a simple example where I import a class and build for production: https://www.diffchecker.com/MBZsEotj. @babel/plugin-transform-runtime {corejs: 3} (left) gives us ~700 extra lines on top of our (already) polyfilled 49 lines code.

The plugin is characterized as a plugin that enables the re-use of Babel's injected helper code to save on codesize, but I could not generate a single example where the size was reduced.

With v4.0.6 there is a new error [#2114] now (but only if using webpack-dev-server)

corejs: false

worked for me

Everyone with this issue: Please check your personal babel.config.js against the default babel.config.js:

  • Inside your projects babel.config.js:

    • Around line 33 of @babel/preset-env should contain corejs: 3

    • Around line 61 of @babel/plugin-transform-runtime should contain corejs: false

PR: https://github.com/rails/webpacker/pull/2116

I'm going to keep this issue open for a while to ensure the problem has been fixed for good.

Awesome, thanks @jakeNiemiec! Can confirm the latest version works on both a fresh and existing app.

Think we can close, as this was fixed in the 4.0.7 release. Thanks again @jakeNiemiec

Was this page helpful?
0 / 5 - 0 ratings

Related issues

eriknygren picture eriknygren  ·  3Comments

christianrojas picture christianrojas  ·  3Comments

ankitrg picture ankitrg  ·  3Comments

FrankFang picture FrankFang  ·  3Comments

ijdickinson picture ijdickinson  ·  3Comments