babel / babel-loader

📦 Babel loader for webpack
MIT License
4.83k stars 451 forks source link

Different transpilation/bundling behavior between ES6 and CJS modules #757

Open veltman opened 5 years ago

veltman commented 5 years ago

[Note: unclear to me whether this issue comes from Webpack, Babel, or the combination of the two, @Timer suggested bringing this here]

Webpack Version: 4.19.1

Babel Core Version: 6.26.3

Babel Loader Version: 8.0.4

Please tell us about your environment: OSX

Current behavior:

Importing a file with rest/spread syntax in it as an ES6 module is properly transpiled/bundled, but importing it as a CJS module causes an error. The error message given is either

Attempted import error: './cjs.js' does not contain a default export (imported as 'cjs').

or

TypeError: Cannot assign to read only property 'exports' of object '#<Object>'

depending on whether it's the first or subsequent build attempt.

Expected/desired behavior:

Both files should be properly imported and transpiled.

Steps to reproduce

Full repro: https://github.com/veltman/webpack-babel-bug-repro

  1. Create a vanilla create-react-app app with react-scripts@2.1.2.

  2. Create two files: src/es6.js and src/cjs.js.

// es6.js
export default ({ foo, ...rest }) => true;

// cjs.js
module.exports = ({ foo, ...rest }) => true;
  1. Run npm start or yarn start.

  2. Import both of them into App.js, one at a time:

import es6 from "./es6.js";
// then
import cjs from "./cjs.js";

This appears to be specific to the language features being used. If I replace the rest/spread with plain destructuring (({ foo, bar }) => true), both files work, they're transpiled and bundled without an error.

veltman commented 5 years ago

Also posted to https://github.com/webpack/webpack/issues/8613 and https://github.com/facebook/create-react-app/issues/6163

fritz-c commented 5 years ago

I created a repo demonstrating this issue as I was preparing my own separate bug report. I see now that my ticket was a duplicate, but at least I can share the repo: https://github.com/fritz-c/import-issue-repro

nicolo-ribaudo commented 5 years ago

The problem is probably that you are transpiling cjs modules as if they were es modules. You need to pass sourceType: script (or unambiguous) to Babel for those files.