Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Unable to validate computed reference to imported namespace

Not sure if I need to add another jshint library or if I should do this a different way.

I have a file (for explanations reasons we'll call it stuff-functions.js) that exports functions like this...

export function a() {
    return 'stuff';
}

export function b() {
    return 'more stuff';
}

export function c() {
    return 'even more stuff';
}

In another file I'm importing that file and calling that function by an argument...

import * as stuffFunctions from './stuff-functions'

export default class someReactClass {
    myFunc(functionToCall) {
        return stuffFunctions[functionToCall]();
    }
    ...
}

It works fine, but in the console I'm getting an eslint error...

Unable to validate computed reference to imported namespace 'stuffFunctions'

So, should I go about this differently or hunt down some sort of eslint library that allows for this?

EDIT...

I've added this line to stop the error // eslint-disable-line

I was just curious if there was a better way to do this. Maybe something like...

import {a, b, c} from './stuff-functions';

export default class someReactClass {
    myFunc(functionToCall) {
        const myStuffFunctions = {
            a: a,
            b: b,
            c: c
        };

        return myStuffFunctions[functionToCall]();
    }
    ...
}

Seems redundant though. :/

like image 571
Bruce Smith Avatar asked Sep 20 '16 15:09

Bruce Smith


1 Answers

The error is being reported by the import/namespace rule in the eslint-plugin-import plugin. It's occurring because you are deciding which imported function will be called at runtime:

stuffFunctions[functionToCall]();

The plugin's static analysis cannot verify that this is a valid import and it reports it as an error.

The simplest solution would be to add an ESLint comment to reconfigure the rule to allow computed references:

/*eslint import/namespace: ['error', { allowComputed: true }]*/
import * as stuffFunctions from './stuff-functions'

export default class someReactClass {
    myFunc(functionToCall) {
        return stuffFunctions[functionToCall]();
    }
    ...
}
like image 151
cartant Avatar answered Nov 16 '22 01:11

cartant