5

I would like to do this

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

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

Thijs Koerselman
  • 16,219
  • 15
  • 62
  • 89
  • 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. – lemieuxster Jan 28 '15 at 18:01
  • @lemieuxster My ES6 code is compiled by a Grunt Browserify [6to5](https://6to5.org/) 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. – Thijs Koerselman Jan 28 '15 at 19:15
  • Was looking for the same answer. Thanks. – captainill Apr 08 '15 at 23:27

1 Answers1

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';

widged
  • 2,550
  • 17
  • 24
  • 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 :) – Thijs Koerselman Sep 01 '15 at 13:52
  • Thanks for pointing that out. Done. – widged Sep 03 '15 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 03 '15 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 '16 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 '17 at 16:29