Saturday, 8 April 2017

Javascript: How to require using const

There's one thing I don't understand about modern Javascript. I see a lot of people discussing whether they should use var, const, or let when requiring new modules. Most people say it's const as their first priority and let second, but I don't see many people who are fan of var. However, this code down below would throw a error TS2451: Cannot redeclare block-scoped variable 'other' error. (Note: This error comes from the Typescript compiler, using the commonjs flag.)

main.js

'use strict';

const A = require('./A.js');
const B = require('./B.js');

// do more stuff

A.js

'use strict';
const other = require('./other.js');

class A {
    //...
};

module.exports = A;

B.js

'use strict';
const other = require('./other.js');

class B {
    //...
};

module.exports = B;

I'm not sure in which cases it's error-less to use const. It seems that it only works when a module is imported in the main module using const, and then everything else in other modules have var for importing the same module. I'd like to know if I'm missing something. Thanks.



via Felo Vilches

No comments:

Post a Comment