Skip to content
Advertisement

Spreading es6 import statements where they are used

In a js file that has no top-level code running, (it just exports functions), should every import statement be placed at the top of the file? Or can I spread them where they make more syntactic sense to me?

Does this affect performance and would you consider such code “hard to read”?

Example (all on top):

import { multiply } from "./multiplication.js";
import { add } from "./addition.js";
import { toPower } from "./exponentiation.js";

export function computeMagicNumber(x, y, z) {
    let magic = linearOperation(x, y);
    magic = exponentOperation(magic, z);
    return magic;
}

function linearOperation(...) {
    // uses multiply() and add()
}

function exponentOperation(...) {
    // uses toPower()
}

Example (spread, so that it is closer to where it is used):

export function computeMagicNumber(x, y, z) {
    let magic = linearOperation(x, y);
    magic = exponentOperation(magic, z);
    return magic;
}


import { multiply } from "./multiplication.js";
import { add } from "./addition.js";

function linearOperation(...) {
    // uses multiply() and add()
}


import { toPower } from "./exponentiation.js";

function exponentOperation(...) {
    // uses toPower()
}

Advertisement

Answer

Does this affect performance?

No. The two modules work exactly the same.

Would you consider such code “hard to read”?

Yes. The established best practice is to put imports at the top of the file, so that you don’t have to search through the whole code for them. Also the imports will be evaluated first, before any code in the module, and will be available in the whole module scope, so it makes sense to declare them in linear order.

If you want your imports closer to the functions that use them, consider using smaller modules, i.e. putting each function in a separate module.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement