使用index.js导出/导入node.js es6 [英] node.js es6 export / import with index.js

查看:171
本文介绍了使用index.js导出/导入node.js es6的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下文件夹结构

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

src / lib / test.js

src/lib/test.js

export default class Test {}..

src / index.js

src/index.js

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

examples / example.js

examples/example.js

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

=> App is undefined

如何设置index.js作为入口点并在那里导出应用程序?

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

编辑:
我正在使用babel-node作为编译器,并以

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

nodemon test.js --exec babel-node --presets es2015,stage-2 --watch ./../..


推荐答案

导入导出本身不受节点支持。

The import and export is not natively supported by Node.

如果要使用该语法,则需要使用Babel这样的编译器。

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

节点方式是使用 module.exports 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?

此处:

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

您不是在导出 from,而是从中导入。

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

也许你是说:

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

然后可以依次导出。

使用正常的Node语法,将是:

With normal Node syntax it would be:

src / lib / test.js

src/lib/test.js

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

src / index.js

src/index.js

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

examples / example.js

examples/example.js

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

还要注意,根据目录结构,您的路径不正确:应为 ./ lib / test.js 而不是 ./ src / lib / test.js ../ 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 ./../..

这篇关于使用index.js导出/导入node.js es6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆