2017-08-24 65 views
2

使用ES6和讓與出口/進口和噶/的WebPack /常量 - 出口在頂部

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:的package.json的

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

及相關零部件:

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

    }, 

回答

4

ES模塊導入反映模塊出口的狀態。儘管const decaration未被懸掛,但在export { test }被評估時,它處於臨時死區,但當模塊導入時,導出已反映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模塊的編碼習慣。

+1

是的,絕對是一個巴別塔的錯誤。 – loganfsmyth