babel-loader
babel-loader copied to clipboard
Different transpilation/bundling behavior between ES6 and CJS modules
[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
-
Create a vanilla create-react-app app with [email protected].
-
Create two files: src/es6.js and src/cjs.js.
// es6.js
export default ({ foo, ...rest }) => true;
// cjs.js
module.exports = ({ foo, ...rest }) => true;
-
Run npm start or yarn start.
-
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.
Also posted to https://github.com/webpack/webpack/issues/8613 and https://github.com/facebook/create-react-app/issues/6163
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
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.