export { test };
const test = (str) => {
return str;
};
import { test } from './func';
describe('func', () => {
describe('func', () => {
it('should return the same string', () => {
expect(test('hello world')).to.equal('hello world');
});
});
});
我想,由于提升,测试函数未定义。
因为如果我这样做:
const test = (str) => {
return str;
};
export { test };
测试有效。
但是,我想将导出内容保留在文件顶部以便于引用。
有什么办法可以实现这一点吗?
我的 karma.conf.js:
const webpackConfig = require('./webpack.config');
const fileGlob = 'src/**/*.test.js';
module.exports = (config) => {
config.set({
basePath: '',
frameworks: ['mocha', 'chai'],
files: [fileGlob],
preprocessors: {
[fileGlob]: ['webpack']
},
webpack: webpackConfig,
webpackMiddleware: {noInfo: true},
reporters: ['progress', 'mocha'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['Firefox'],
singleRun: true,
concurrency: Infinity,
});
};
以及package.json的相关部分:
"devDependencies": {
"webpack": "^3.5.5",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-plugin-add-module-exports": "^0.2.1",
"babel-preset-es2015": "^6.24.1",
"chai": "^4.1.1",
"mocha": "^3.5.0",
"karma": "^1.7.0",
"karma-chai": "^0.1.0",
"karma-mocha": "^1.3.0",
"karma-webpack": "^2.0.4",
},
最佳答案
ES模块导入反射(reflect)了模块导出的状态。即使 const
解析没有被提升,但在评估 export { test }
时它处于临时死区,但是当导入模块时,export 已经反射(reflect)了 test
实际值。
该问题可能是由模块转译引起的不正确行为造成的。通天塔doesn't implement module exports correctly ,这会导致导出未定义
。
可以看出here (在支持 ES 模块的浏览器中可用,即最新的 Chrome),模块导出按 native 预期工作。
TypeScript handles exports as intended ,也是。
为了使代码与现有实现兼容,应该是:
export const test = (str) => {
return str;
};
或者:
const test = (str) => {
return str;
};
export { test };
这两种方式都是传统的导出方式,特别是因为这个问题。模块末尾的导出符合使用 CommonJS 模块所产生的编码习惯。
关于javascript - 使用 ES6 和 let/const 以及导出/导入和 Karma/webpack - 导出在顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45864687/