I don’t understand a syntax that there is no comma after the declaration of a function within an array

Asked

Viewed 27 times

1

The bold part, because there is a comma between the parentheses, I found no reference to this writing.

module.exports = {
    plugins: [
        require("postcss-uncss"**)(**{
            html: [
                './index.html'
            ]
        })
    ]
}
  • It is important to remember, although it works, this is probably not a good idea, in many languages the import of other files is always done at the beginning of the file, even those that are not mandatory also do this, is a standard adopted by all, not to use this standard, You must have a reason. Also, this form does not allow reuse, if somewhere else you want to use the module, you will have to reimport it, or use the default at the beginning of the file save the module to a variable, and if this is done, can leave the messy code importing only a few modules at the beginning and others not

1 answer

2

There is no comma because this is all just a value. What is happening there is not the statement of a function, it is the call of a function.

That:

module.exports = {
    plugins: [
        require("postcss-uncss")({
            html: [
                './index.html'
            ]
        })
    ]
}

That’s the equivalent of:

const postcssUncss = require("postcss-uncss");
const postcssPlugin = postcssUncss({ html: ['./index.html'] });

module.exports = {
    plugins: [postcssPlugin]
}

You are importing the module postcss-uncss, that is exposing a function, and immediately you invoke the function by passing the parameter { html: ['./index.html'] }. Her return is the value passed to the array plugins.

  • Is the call from require ali in case it is returning an anonymous function and being immediately invoked? Has a technical name for this or article?

  • The function is not necessarily anonymous, it is a function that was exported by the module you imported, whether it was declared with a name or anonymously is irrelevant. I don’t think there is a specific name for this style. When you declare and invoke a function immediately, this is called IIFE, but I’ve never seen anyone refer to the act of importing and invoking a function like IIFE.

  • I think I saw something like this in the little functional programming I saw, I think it’s called currying, I wasn’t remembering, but I can’t confirm.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.