Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

require is not defined with es6 native modules => wrong import path and require fonction in webpack output #294

Closed
rvion opened this issue Jan 15, 2021 · 24 comments · Fixed by #337 or #492

Comments

@rvion
Copy link

rvion commented Jan 15, 2021

I get a

🔴 ReferenceError require is not defined

📝I use esm native modules.
📝My config matches the readme

but webpack generate a weird import line for __webpack_require__.$Refresh$.runtime for every module:

                            WRONG REQUIRE v                         WRONG PATH v
__webpack_require__.$Refresh$.runtime = require('C:/Users/myusername/dev/devops-cli/node_modules/react-refresh/runtime.js');

🔍it is as if it was not using the correct require, nor rewriting properly the path.

You can find more details below as well as a longer extract from webpack output.
What else can I provide ?

Any help or workaround appreciated ! 👍


config:

plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new ReactRefreshWebpackPlugin(),
]
....
module: {
    rules: [
        {
            // https://github.com/pmmmwh/react-refresh-webpack-plugin
            test: /\.js$/,
            exclude: /node_modules/,
            use: [
                {
                    loader: require.resolve('babel-loader'),
                    options: { plugins: [require.resolve('react-refresh/babel')], },
                },
            ],
        },
    ]
}

misc packages versions:

  • "@pmmmwh/react-refresh-webpack-plugin": "0.4.3",
    ...
  • "@babel/core": "7.12.10",
  • "@babel/plugin-proposal-decorators": "^7.12.12",
  • "@babel/plugin-transform-react-jsx": "^7.12.12",
  • "@babel/preset-react": "^7.12.10",
  • "@babel/preset-typescript": "^7.12.7",
    ...
/***/ "./packages/test/counterUI1.js":
/*!*************************************!*\
  !*** ./packages/test/counterUI1.js ***!
  \*************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "CounterUI": () => /* binding */ CounterUI,
/* harmony export */   "foo": () => /* binding */ foo
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var _emotion_react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @emotion/react */ "./node_modules/@emotion/react/dist/emotion-react.browser.esm.js");
/* provided dependency */ var __react_refresh_utils__ = __webpack_require__(/*! ./node_modules/@pmmmwh/react-refresh-webpack-plugin/lib/runtime/RefreshUtils.js */ "./node_modules/@pmmmwh/react-refresh-webpack-plugin/lib/runtime/RefreshUtils.js");
/* provided dependency */ var __react_refresh_error_overlay__ = __webpack_require__(/*! ./node_modules/@pmmmwh/react-refresh-webpack-plugin/overlay/index.js */ "./node_modules/@pmmmwh/react-refresh-webpack-plugin/overlay/index.js");
                                            v HERE v 
__webpack_require__.$Refresh$.runtime = require('C:/Users/rvion/dev/devops-cli/node_modules/react-refresh/runtime.js');
__webpack_require__.$Refresh$.setup(module.id);

Thanks

@rvion rvion changed the title require is not defined with es6 native modules => wrong import path and requrie fonction in webpack output require is not defined with es6 native modules => wrong import path and require fonction in webpack output Jan 15, 2021
@pmmmwh
Copy link
Owner

pmmmwh commented Jan 18, 2021

Hi, thanks for reporting this bug. I think this has something to do with our way of injecting dependencies via a loader. I can publish a beta version that might fix this, would you mind trying it out to see if it works or provide a minimal native ESM webpack project for reproduction?

@SamMorrowDrums
Copy link

@pmmmwh I would happily. I'm having same issue.

@rvion
Copy link
Author

rvion commented Jan 22, 2021

thanks @pmmmwh ! I can't test easily right now, since I reverted most of my changes related to migrating to esnext. (Too many things broken across various utilities I use) Thanks anyway for the quick feedback.

thanks @SamMorrowDrums for stepping in !

@16patsle
Copy link

I'm also seeing this issue, with a relatively minimal webpack config. Everything should be up to date, since I set up this project only a few days ago. Let me know if there's anything I can do to help.

webpack.config.js
const path = require("path");
const HtmlWebPackPlugin = require('html-webpack-plugin')
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin')

const createConfig = isDevelopment => ({
  entry: path.resolve(__dirname, 'src/index.js'),
  //target: isDevelopment ? 'web' : 'browserslist',
  output: {
    path: path.resolve(__dirname, "dist"),
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            plugins: [
              isDevelopment && require.resolve('react-refresh/babel'),
            ].filter(Boolean),
          },
        },
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader', 'postcss-loader'],
      },
    ],
  },
  plugins: [
    new HtmlWebPackPlugin({
      template: './src/index.html',
    }),
    isDevelopment && new ReactRefreshWebpackPlugin(),
  ].filter(Boolean),
})

module.exports = (env, argv) => createConfig(argv.mode === 'development')
Also .babelrc, just in case
{
  "presets": [
    [
      "@babel/preset-env",
      {
        "bugfixes": true,
        "useBuiltIns": "usage",
        "corejs": "3.8",
        "shippedProposals": true
      }
    ],
    "@babel/preset-react"
  ]
}

@pmmmwh
Copy link
Owner

pmmmwh commented Jan 23, 2021

Hi, I'm implementing a fix for this issue. Just so I can understand the issue more, are you all running native ESM with Webpack 5+? My impression is that the fix might not work quite well in Webpack 4 if you run strict ESM (where module is not available).

@16patsle
Copy link

Thanks. I'm using the latest version of Webpack 5 yes.

@jeremytenjo
Copy link

jeremytenjo commented Feb 20, 2021

Any updates with this fix?

@pmmmwh
Copy link
Owner

pmmmwh commented Feb 23, 2021

A fix should be ready this week. I'm planning to ship 0.5.0 within February.

@jeremytenjo
Copy link

A fix should be ready this week. I'm planning to ship 0.5.0 within February.

Great! Thank you 👍

@xiaoshuangLi
Copy link

I got same error, because i defined require function.

WechatIMG3416

@dmnsgn
Copy link

dmnsgn commented Mar 9, 2021

Hi @pmmmwh,

I have tried 5.0.0-beta.1 but __webpack_require__.$Refresh$.runtime is still using a require() call. Is there a specific options than needs to be used or the fix you mention above is not implemented yet? Thanks

@pmmmwh
Copy link
Owner

pmmmwh commented Mar 9, 2021

Hi, unfortunately the semantics needed for the fix is a bit more complex than expected.

The runtime is currently in a half-baked state where some tests pass and some don't (hopefully some progress in a PR soon). I'm continuously working on it currently.

In particular, some blockers:

@sokra
Copy link

sokra commented Mar 11, 2021

  • currently fixed but unreleased

I'll try to release this today. The error semantics are the following with this change:

  • The dispose handler of the old module is called.
  • The new module factory is called (module evaluation)
  • Any error during module evaluation will lead to an "module" in error state in the module cache. module.error is set to this error.
    • This also applies for compilation errors when optimization.emitOnErrors: true is set.
    • Note that the module might have partially executed until the point of the error!!
    • This is a new module, which is !== the old module.
  • A self accept error handler of the old module is called with the runtime error that occured.
    • It also gets access to the new module via the module property in the second argument
    • It might use the HMR api of the new module module.hot
  • The new module might or might not have self accepted.
    • It depends if accept was called before the error occured
    • Even if the accept call is the first statement, it might not call it, when compilation errors or parse errors occur.
    • There can only be one self accept error handler. Calling accept twice will override it.
  • The new module might or might not have registered a dispose handler.
    • Some like above
    • There can be multiple dispose handlers. Calling addDisposeHandler twice will add multiple.
    • removeDisposeHandler can be used to remove handlers
    • You can use import.meta.webpackHot.data to store state in module evaluation and access this later via module.hot.data in the self accept error handler.
  • If you self accept the new module in the self accept error handler, make sure to also register a dispose handler to not loose data.
  • It's now possible to handle errors in import.meta.webpackHot.accept("./dep", ...) too, but I think you don't use that anyway.

@swissspidy
Copy link

I there any update on this, anything people can help with?

@pmmmwh
Copy link
Owner

pmmmwh commented Mar 25, 2021

I'll try to push out the WIP new runtime on this tonight.

@ntucker
Copy link

ntucker commented Jun 30, 2021

I'm experiencing this problem in the latest rc with a package that uses the new package.json 'exports' member to define es6 modules.

reactive/data-client#996
yarn install
cd examples/todo-app
yarn start

@2heal1
Copy link

2heal1 commented Jul 15, 2021

I got same error, because i defined require function.

WechatIMG3416

so do i,have you solved this problem?

@pmmmwh
Copy link
Owner

pmmmwh commented Jul 15, 2021

so do i,have you solved this problem?

Rename the function. require is a global in the CommonJS module system, there's nothing we can do about it.

@ipsips
Copy link

ipsips commented Aug 28, 2021

i can confirm that this is still broken in 0.5.0-rc.5

Screenshot 2021-08-28 at 12 20 59

@pmmmwh
Copy link
Owner

pmmmwh commented Aug 29, 2021

i can confirm that this is still broken in 0.5.0-rc.5

This has something to do with monorepo compatibility, it will be addressed in the next RC.

@ntucker
Copy link

ntucker commented Aug 29, 2021

Thanks @pmmmwh that's good to hear! <3

@ghost
Copy link

ghost commented Dec 24, 2021

I'm having the same problem.

After some debuging I found that the problem first occurs in the file node_modules/webpack/hot/emitter.js at its very first line:

var EventEmitter = require("events");   // <--The problem first happens here
module.exports = new EventEmitter();

Obviously, I hacked this file this way:

// var EventEmitter = require("events"); 
import EventEmitter from "events"
export default new EventEmitter();

Then, fortunately, the error 'required is not defined' was gone in this file but, unfortunately, it occurred in the file ./dev-server.js, in the same directory.

It was clearly begging me for another hacking, what I did in this way:

// var hotEmitter = require("./emitter");
import('./emitter')
	  .then( hotEmitter => {
	     hotEmitter.on("webpackHotUpdate", function(currentHash) {
	    	lastHash = currentHash;
		if (!upToDate() && module.hot.status() === "idle") {
			log("info", "[HMR] Checking for updates on the server...");
			check();
		}
             });
	     log("info", "[HMR] Waiting for update signal from WDS...");
	  });

Again, the error was gone in that file but, to my despair, the error moved to another place related to a require chunk loading thing.

I guess that this has to be with a comment made by @pmmmwh above:

unfortunately the semantics needed for the fix is a bit more complex than expected.

At the end, I'm under the impression that the (Webpack) code is a little "spaghettified" in that module - which represents a good opportunity for improvements - and that wouldn't be very easy to fix the problem.

Does it make sense? Please, let me know.

@pmmmwh
Copy link
Owner

pmmmwh commented Dec 25, 2021

I'm having the same problem.

After some debuging I found that the problem first occurs in the file node_modules/webpack/hot/emitter.js at its very first line:

This sounds like either a bug on Webpack's side (what version are you using?) or a misconfiguration with your ESM setup. These files are internals of Webpack HMR and should not have to be touched for things to work.

@Param1raj
Copy link

Did you find the required configurations of webpack or ESM setup to make this work?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet