Search code examples
javascriptwebpackbabeljswebpack-4babel-loader

How to configure babel7 to support `import {}` from `export default` in javascript


I am using webpack 4 and babel 7 for a javascript project. I doesn't work when I use import { ... } syntax. Below is the source code:

./test.js

const a = 1;

export default { a };

./index.js

import { a } from './test';

console.log(a);

The output is undefined. It works fine if I change index.js as below:

import a from './test';

console.log(a.a);

I wonder how I should configure babel7 to support import {}. Below is my .babelrc:

{
  "presets": [
    "@babel/preset-env"
  ]
}

I also tried a few plugins but none of them works:

{
  "presets": [
    "@babel/preset-env"
  ],
  "plugins": [
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-transform-async-to-generator",
    "@babel/plugin-proposal-object-rest-spread",
    "@babel/plugin-proposal-export-default-from",
    "@babel/plugin-syntax-export-default-from",
    "@babel/plugin-proposal-export-namespace-from"
  ]
}

Below is the dependencies:

devDependencies": {
    "@babel/cli": "^7.2.3",
    "@babel/core": "^7.2.2",
    "@babel/plugin-proposal-class-properties": "^7.2.3",
    "@babel/plugin-proposal-decorators": "^7.2.3",
    "@babel/plugin-proposal-export-default-from": "^7.2.0",
    "@babel/plugin-proposal-export-namespace-from": "^7.2.0",
    "@babel/plugin-proposal-object-rest-spread": "^7.2.0",
    "@babel/plugin-syntax-export-default-from": "^7.2.0",
    "@babel/plugin-transform-arrow-functions": "^7.2.0",
    "@babel/plugin-transform-async-to-generator": "^7.2.0",
    "@babel/preset-env": "^7.2.3",
    "@babel/preset-es2015": "^7.0.0-beta.53",
    "babel-loader": "^8.0.4",
    "jest": "^23.6.0",
    "webpack": "^4.28.2",
    "webpack-cli": "^3.1.2",
    "webpack-dev-server": "^3.1.14"
  },

Below is my webpack configuration for babel-loader:

module: {
      rules: [
        {
          test: /\.js?$/,
          exclude: /(node_modules)/,
          loader: 'babel-loader'
        }
      ]
    },

Solution

  • This has nothing to do with Babel. The problem is that you need to read up on how named exports work.

    import { a } from './test';
    

    is trying to import the named export a from test.js. The brackets {} syntax is for importing named exports.

    Instead, go with

    import a from './test';
    

    which is the syntax for importing the default export,

    or change test.js to do an export named a:

    const a = 1;
    
    export { a };
    

    Your test.js only has a default export, and none named a.