2 * @fileoverview Rule to enforce a particular function style
3 * @author Nicholas C. Zakas
7 //------------------------------------------------------------------------------
9 //------------------------------------------------------------------------------
16 description: "enforce the consistent use of either `function` declarations or expressions",
17 category: "Stylistic Issues",
19 url: "https://eslint.org/docs/rules/func-style"
24 enum: ["declaration", "expression"]
29 allowArrowFunctions: {
34 additionalProperties: false
39 expression: "Expected a function expression.",
40 declaration: "Expected a function declaration."
46 const style = context.options[0],
47 allowArrowFunctions = context.options[1] && context.options[1].allowArrowFunctions,
48 enforceDeclarations = (style === "declaration"),
51 const nodesToCheck = {
52 FunctionDeclaration(node) {
55 if (!enforceDeclarations && node.parent.type !== "ExportDefaultDeclaration") {
56 context.report({ node, messageId: "expression" });
59 "FunctionDeclaration:exit"() {
63 FunctionExpression(node) {
66 if (enforceDeclarations && node.parent.type === "VariableDeclarator") {
67 context.report({ node: node.parent, messageId: "declaration" });
70 "FunctionExpression:exit"() {
75 if (stack.length > 0) {
76 stack[stack.length - 1] = true;
81 if (!allowArrowFunctions) {
82 nodesToCheck.ArrowFunctionExpression = function() {
86 nodesToCheck["ArrowFunctionExpression:exit"] = function(node) {
87 const hasThisExpr = stack.pop();
89 if (enforceDeclarations && !hasThisExpr && node.parent.type === "VariableDeclarator") {
90 context.report({ node: node.parent, messageId: "declaration" });