如何在JavaScript中将babel7配置为支持来自“导出默认值”的“导入{}”

时间:2018-12-31 08:49:25

标签: javascript webpack babel webpack-4 babel-loader

我正在将webpack 4babel 7用于javascript项目。我使用import { ... }语法时无法工作。下面是源代码:

./ test.js

const a = 1;

export default { a };

./ index.js

import { a } from './test';

console.log(a);

输出为undefined。如果我按如下所示更改index.js,则效果很好:

import a from './test';

console.log(a.a);

我想知道如何配置babel7以支持import {}。以下是我的.babelrc:

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

我也尝试了一些插件,但没有一个起作用:

{
  "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"
  ]
}

下面是依赖项:

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"
  },

以下是我的babel-loader的Webpack配置:

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

1 个答案:

答案 0 :(得分:1)

这与Babel无关。问题在于,您需要阅读命名出口的工作方式。

import { a } from './test';

尝试从a导入命名导出test.js。方括号{}的语法用于导入命名导出。

相反,请选择

import a from './test';

这是导入default导出的语法,

或更改test.js进行名为a的导出:

const a = 1;

export { a };

您的test.js仅导出default,没有一个名为a