5

I would like to do this

var debug = require('debug')('myapp');

... in ES6 without creating an extra variable. Can it be done?

3
  • 1
    Assuming the debug module was set up to support ES6 exports the answer is still essentially "No." There needs to be the import directive then you use the imported bit. import Debug from 'debug'; let debug = Debug('myapp'); or similar. Possibly using System.import would remove the extra object, but it creates a nested function mess. Jan 28, 2015 at 18:01
  • @lemieuxster My ES6 code is compiled by a Grunt Browserify 6to5 transform into CommonJs so the debug module doesn't care. I was just wondering if such a thing is supported in ES6. Thanks for clearing that up. Jan 28, 2015 at 19:15
  • Was looking for the same answer. Thanks.
    – captainill
    Apr 8, 2015 at 23:27

1 Answer 1

13
import Debug from 'debug';

const debug = Debug('myapp');

(as lemieuxster said... addressing the fact that it is still listed under unanswered questions)

Note as mentioned in the comments, this will work for modules exported with the es6 syntax, that is whenever export default expression was used, which would give way to a require of the form var debug = require('./debug').default('myapp');. If the module you are importing used an export syntax of the type export const Debug = expression or export {Debug} or module.exports = {Debug : expression} then you will have to use import {Debug} from 'debug';

5
  • You're destructuring a property that isn't available. Debug is the "default" export and not a seperately exported value / export property afaict. Remove the brackets and I will mark your answer :) Sep 1, 2015 at 13:52
  • Thanks for pointing that out. Done.
    – widged
    Sep 3, 2015 at 11:44
  • Credits should go to @lemieuxster though... I put it as answer because the post was showing up in the unanswered list. If s/he writes his comment as an answer, I am happy to delete mine.
    – widged
    Sep 3, 2015 at 11:47
  • debug module doesn't have any default exports though so this wouldn't work. Although I guess this is only shows when using TypeScript. In that case you'd want to: import * Debug from 'debug' and then const debug = Debug('app')('scope');
    – ken
    Oct 30, 2016 at 13:13
  • @ken you need an as in there - import * as Debug from 'debug';, but then rollup won't like it (cannot call a namespace ('Debug')).
    – WillyC
    Mar 29, 2017 at 16:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.