FormidableLabs / babel-plugin-transform-define

Compile time code replacement for babel similar to Webpack's DefinePlugin
MIT License
245 stars 31 forks source link

ES module identifier imports throwing #69

Closed jdlm-stripe closed 3 years ago

jdlm-stripe commented 3 years ago

Given a file with:

import FOO from './bar';

FOO;

And a babel config of:

module.exports = {
  plugins: [
    [
      "transform-define",
      {
        FOO: "bar"
      }
    ]
  ]
};

The plugin is currently crashing with:

TypeError: test/babel-plugins/define-transform/src/index.js: Property local of ImportDefaultSpecifier expected node to be of a type ["Identifier"] but instead got "StringLiteral"
    at Object.validate (node_modules/@babel/types/lib/definitions/utils.js:130:11)
    at validateField (@babel/types/lib/validators/validate.js:24:9)
    at Object.validate (@babel/types/lib/validators/validate.js:17:3)
    at NodePath._replaceWith (@babel/traverse/lib/path/replacement.js:147:7)
    at NodePath.replaceWith (@babel/traverse/lib/path/replacement.js:129:8)
    at replaceAndEvaluateNode (babel-plugin-transform-define/lib/index.js:37:12)
    at processNode (babel-plugin-transform-define/lib/index.js:62:5)
    at PluginPass.Identifier (babel-plugin-transform-define/lib/index.js:82:9)
    at newFn (@babel/traverse/lib/visitors.js:171:21)
    at NodePath._call (@babel/traverse/lib/path/context.js:53:20) {
  code: 'BABEL_TRANSFORM_ERROR'
}

Given that original file, I believe it should be unchanged if there's an ES module import in scope of the same name.

For context this is how webpack renders the same file:

<snip>
/*!**********************!*\
  !*** ./src/index.js ***!
  \**********************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _bar__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bar */ "./src/bar.js");

_bar__WEBPACK_IMPORTED_MODULE_0__["default"];

/***/ })
<snip>

That's a little hard to read. Essentially I don't think this plugin should transform identifiers if they're defined as imports from other modules. I ran into this bug in a real-world code base.

I'll be putting up a PR with a fix shortly but wanted to file this issue first to make sure you folks are amenable to my proposed fix.