我正在将webpack 4
和babel 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'
}
]
},
答案 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
。