Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js es6 export / import with index.js

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 ./../..
like image 888
user345234674567 Avatar asked Oct 17 '22 09:10

user345234674567


2 Answers

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:

  • Is it ok to use Babel npm package for node.js server application
  • javascript - Why is there a spec for sync and async modules?
  • What is the syntax to export a function from a module in Node.js?

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 ./../..

like image 107
rsp Avatar answered Oct 20 '22 23:10

rsp


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 '../'
like image 22
cstuncsik Avatar answered Oct 21 '22 01:10

cstuncsik