2017-06-29 29 views
0

我遵循指導在我的react-native應用程序中實施REDUX。我想實現行動但我eslint不斷給予8日這個錯誤線 -導出ES6中聲明爲常量的函數

[eslint] Prefer default export. (import/prefer-default-export) 

我的代碼 -

import * as types from './types'; 

const incrementCounter = counterValue => ({ 
    type: types.INCREMENT_COUNTER, 
    counterValue, 
}); 

export { incrementCounter }; 

我的問題是什麼是導出這個常量的正確方法在ES6中的功能?

+1

你的語法很好。 ESLint會觸發,因爲根據您的規則,如果您的模塊*只有一個導出*,那麼它應該是*默認*。根據這條規則,如果你有多個,你應該只'輸出{...}。堅持你的規則:'出口默認incrementCounter' – CodingIntrigue

+0

謝謝,它的工作。 :) –

回答

2

最簡單的變化將是as default添加到您的export { incrementCounter };。然而,爲了導出函數作爲默認的導出你使用default exports而寫

import * as types from './types'; 

export default counterValue => ({ 
    type: types.INCREMENT_COUNTER, 
    counterValue, 
}); 

import * as types from './types'; 

export default function incrementCounter(counterValue) { 
    return { 
    type: types.INCREMENT_COUNTER, 
    counterValue, 
    }; 
} 
+0

第一個錯誤'[eslint]解析錯誤:'const'上的意外標記'也出錯。 –

+0

@KaranHudia你是對的,那應該是'export default counterValue => ...'而不是'const'。 – CodingIntrigue

1

在config.js

// Declaration of const 

const config = { 
    name: 'test' 
}; 

export default config 

在另一個文件

// Using const 

import * as config from '../config'; 

let name = config.name; 
+0

那麼'module.exports'並不是真正的ES6方式。 –

+0

我已經更新了我的回答 –

1

import/prefer-default-export是有問題的規則, 你將失去​​類型一致性和你IDE將不再能夠幫助您進行重構,檢查和代碼完成。

你將總是能夠用進口別名一個不同的名稱導入:import {incrementCounter as foo} from 'incrementCounter'

它可以表現爲個人的意見,但是,我強烈建議你保持named exports和編輯您.eslintrc

{ 
    "rules": { 
    "import/prefer-default-export" : 0 
    } 
} 

請參閱本討論: https://github.com/airbnb/javascript/issues/1365

+1

你能解釋第一段嗎?當涉及到IDE時,爲什麼它與命名導出不同? – CodingIntrigue

+0

由於引用不明確,請按照github上的討論。 – Hitmands

+0

我讀了討論。我也讀過作者的想法,並同意重構是在*文件*中。有點像說避免'import as'因爲它不能被重構。每個都有它自己的邊緣情況,但默認的導出規則只是保持最小文件以避免重構。無論如何,IMO :) – CodingIntrigue