Angular 5中NGRX Reducer适配AOT编译报错求助
解决NGRX Store从JIT转AOT时
accountReducer的导出函数错误 我完全懂你切换AOT编译器时碰到的这个麻烦——AOT对代码的静态分析要求比JIT严格得多,你现在用箭头函数表达式定义accountReducer的方式,没办法被AOT编译器正确识别,所以才会抛出这个错误:
'accountReducer' contains the error at app/store/account/account.reducer.ts(19,64) Consider changing the function expression into an exported function.
这个修复其实特别简单,只需要调整account.reducer.ts里的reducer定义方式,把函数表达式改成具名导出函数就行,核心逻辑完全不用动。
修改后的account.reducer.ts代码
import { ActionReducer, Action } from '@ngrx/store'; import { tassign } from 'tassign'; import { saveState, rehydrateState, rehydrateAction } from 'helpers'; import { DefaultAction } from 'interfaces'; import { AccountConstants } from './account.constants'; import { AccountInterface } from './account.interface'; export const initialAccountState: AccountInterface = { account: null, hash: { isLoading: true, isAccepted: false, }, isLoggedIn: false, }; // 把原来的箭头函数表达式改成具名导出函数 export function accountReducer(state: AccountInterface = initialAccountState, action: DefaultAction) { const { type, payload } = action; let newState: any = state; switch (type) { case AccountConstants.ACTION_ACCOUNT_LOGOUT_ACCOUNT: newState = tassign(initialAccountState); break; case AccountConstants.ACTION_HASH_DENIED: newState = tassign(state, { hash: { isLoading: false, isAccepted: false, }, }); break; case AccountConstants.ACTION_HASH_ACCEPTED: newState = tassign(state, { hash: { isLoading: false, isAccepted: true, }, }); break; case rehydrateAction: const rehydratedState = rehydrateState('account'); newState = tassign(state, rehydratedState); break; } if (type !== rehydrateAction) { saveState('account', newState); } return newState; }
关键修改点
原来的代码是用const赋值箭头函数:
export const accountReducer: ActionReducer<AccountInterface> = (state: AccountInterface = initialAccountState, action: DefaultAction) => { // ...逻辑 };
现在改成了标准的export function声明:
export function accountReducer(state: AccountInterface = initialAccountState, action: DefaultAction) { // ...逻辑 }
其他文件无需修改
你的root.reducer.ts和app.module.ts完全不用调整,因为它们只是导入并使用accountReducer,修改后的函数导出和原来的常量导出在导入时的用法完全一致。
通用提示
如果之后你的其他NGRX reducer也碰到类似的AOT错误,都可以用这个方法解决:把箭头函数表达式定义的reducer,改成具名的export function就行——这是AOT编译器对可静态分析代码的基本要求。
内容的提问来源于stack exchange,提问作者rvdm
相关产品推荐
相关产品推荐

