使用 ES6 和 let/const 导出/导入和 Karma/webpack - 导出在顶部

Using ES6 and let/const with export / import and Karma/webpack - export at the top

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');
        });
    });
});

test-function 由于提升而未定义,我想。 因为如果我这样做:

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模块导入反映了模块导出的状态。虽然constdecaration没有挂起,在export { test }求值的时候处于暂时死区,但是当模块导入export时已经反映了test实际值。

该问题可能是由模块转译引起的不正确行为引起的。 Babel doesn't implement module exports correctly,这导致 undefined 导出。

可以看出here(在支持 ES 模块的浏览器中可用,即最新的Chrome),模块导出按本机预期工作。

TypeScript handles exports as intended,也是。

为了使代码与现有的实现兼容,应该是:

export const test = (str) => {
    return str;
};

或者:

const test = (str) => {
    return str;
};

export { test };

这两种都是传统的导出方式,尤其是因为这个问题。模块末尾的导出符合使用 CommonJS 模块导致的编码习惯。