7

I have the following folder structure

src/
  index.js
  lib/
    test.js
dist/
examples/
  example.js

src/lib/test.js

export default class Test {}..

src/index.js

import App from './lib/test.js'
export default App

examples/example.js

import {App} from './../..'

=> App is undefined

How can I set my index.js as entrypoint and export my app there?

edit: I'm using babel-node as transpiler and start it with

nodemon test.js --exec babel-node --presets es2015,stage-2 --watch ./../..
user345234674567
  • 321
  • 1
  • 4
  • 17

2 Answers2

3

The import and export is not natively supported by Node.

You need to use a transpiler like Babel if you want to use that syntax.

The Node way is to use module.exports and require().

See this for more info:

Update

Here:

export {default as App} from './src/lib/test.js'

you're not exporting "from" - you import from.

Maybe you meant:

import App from './src/lib/test.js';

and then you can export that in turn.

With normal Node syntax it would be:

src/lib/test.js

class Test {
  // ...
}
module.exports = { Test };

src/index.js

const { Test: App } = require('./lib/test.js');

examples/example.js

const { App } = require('../src');

Also note that according to your directory structure your paths are incorrect: it should be ./lib/test.js instead of ./src/lib/test.js and ../src instead of ./../..

rsp
  • 107,747
  • 29
  • 201
  • 177
  • 1
    But then the OP would get a syntax error, not `undefined`, no? – Felix Kling Jul 18 '17 at 19:12
  • I'm using babel-node as transpiler to start it with "nodemon test.js --exec babel-node --presets es2015,stage-2 --watch ./../.." – user345234674567 Jul 18 '17 at 19:12
  • 1
    @coffeecup It would be much easier to answer your questions if you included the relevant info in the question in the first place. – rsp Jul 18 '17 at 19:13
  • I changed export class to "export default" in my test.js file, and changed the export from.. to import test from in my index.js, now when I console.log(test) I can see [Function: App]. How would I export this properly to be able to import it in my example.js? – user345234674567 Jul 18 '17 at 19:34
  • my index.js is import Test from ..... and export default Test, but in my example.js it's still undefined – user345234674567 Jul 18 '17 at 19:39
1

I would just put src/index.js as main in the package.json and just run nodemon without the watch param.

By default nodemon monitors the current working directory. If you want to take control of that option, use the --watch option to add specific paths

Also paths sould look like this:

src/lib/test.js

export default class Test {}

src/index.js

export {default as App} from './lib/test.js'

examples/example.js

import {App} from '../'
cstuncsik
  • 2,698
  • 2
  • 16
  • 20