简体   繁体   中英

Babel.js: Uncaught TypeError: _interopRequireDefault is not a function

I use the babel.js node.js API to compile react jsx and js scripts.

I have the following node.js script for example:

// react_transform.js 

const fs = require("fs");

code = fs.readFileSync("./samples/sample4.js", 'utf8');

result2 = require("@babel/core").transformSync(code, {
    presets: [
        "@babel/preset-env",
        "@babel/preset-react",
    ],
    plugins: [
        "@babel/plugin-transform-runtime",
    ],
});

fs.writeFileSync(`./out/out4.js`, result2.code);

console.log("y.");

And the input file that has the jsx code is like:

// sample4.js

ReactDOM.render(
    <div>
        <p>
            hoge.
        </p>
    </div>
    ,
    document.getElementById('root')
);


$(".__upvote").click(async function (e) {
    alertify.warning("You need to login.");
}); 

Without the "@babel/plugin-transform-runtime", line in the node.js script, when I use the script on the browser (where the output code should be located in the production), it causes an error:

VM496:9 Uncaught ReferenceError: regeneratorRuntime is not defined

So, I did research and added the line. But now I started to get a new error:

VM830:5 Uncaught TypeError: _interopRequireDefault is not a function

By the way the output js file is as follows:

// out4.js 

"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

ReactDOM.render( /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("p", null, "hoge.")), document.getElementById('root'));
$(".__upvote").click( /*#__PURE__*/function () {
  var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(e) {
    return _regenerator["default"].wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            alertify.warning("You need to login.");

          case 1:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));

  return function (_x) {
    return _ref.apply(this, arguments);
  };
}());

So I again did research about the new error, found an SO post:

reactjs - How to fix TypeError _interopRequireDefault is not a function in Create React App - Stack Overflow

People say:

Add @babel/runtime to the dependency section. That will fix it.

After add "@babel/runtime", I fixed it

So I added that "@babel/runtime" to package.json then npm install-ed. Now the package.json is like (I ommited irrelevant lines):

{
    "name": "tmp",
    "version": "1.0.0",
    "description": "",
    "main": "lodash_dev.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "author": "",
    "license": "ISC",
    "dependencies": {
        "@babel/runtime": "^7.17.8",
    },
    "devDependencies": {
        "@babel/plugin-syntax-dynamic-import": "^7.8.3",
        "@babel/plugin-transform-react-jsx": "^7.17.3",
        "@babel/plugin-transform-runtime": "^7.17.0",
        "@babel/preset-env": "^7.16.11",
        "@babel/preset-react": "^7.16.7",
    }
}

Then re-run the node.js script, I get the output, I tested it on the page on the browser, however, for some reason the error still persists.

How can I fix this? Thanks.

You're transforming your code with Babel, but you're not running a bundler such as esbuild or webpack.

require() is not a thing in the browser. The bundler's responsibility (among other things) is to take all of those require() calls and resolve them into real modules, and end up with one (or more).js files that contains all of the require() d code and no require() s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM