如何导出要在ES6中导入的功能?

时间:2018-06-28 04:52:31

标签: javascript node.js

在节点v10.5.0中困惑我在做什么错

[hendry@t480s learn2]$ node --experimental-modules main.mjs
(node:23920) ExperimentalWarning: The ESM module loader is experimental.
file:///tmp/learn2/main.mjs:1
import {hello} from 'module' // or './module'
        ^^^^^
SyntaxError: The requested module 'module' does not provide an export named 'hello'
    at ModuleJob._instantiate (internal/modules/esm/module_job.js:80:21)
[hendry@t480s learn2]$ cat main.mjs
import {hello} from 'module' // or './module'
let val = hello() // val is "Hello";

console.log('hi there')

console.log(val)
[hendry@t480s learn2]$ cat module.mjs
export function hello() {
  return "Hello";
}

export default hello

4 个答案:

答案 0 :(得分:3)

如果模块中只有一个功能,则可以执行以下操作:

export default function hello() {
    return "Hello";
}

并像这样导入它:

import hello from './module'

在导入使用export default导出的模块时,您可以选择一个名称:

import greeting from './module'

您无法使用const导出let varexport default

如果模块中有多个功能,则可以执行以下操作:

export function hello() {
    return "Hello";
}

export function bye() {
    return "Bye";
}

function hello() {
    return "Hello";
}

function bye() {
    return "Bye";
}

export { hello, bye };

并以这种方式导入函数:

import { hello } from './module'

答案 1 :(得分:1)

Hello是默认导出

例如,在react中,React是默认导出,因为这通常是您唯一需要的部分。您不一定总是使用Component,因此这是一个命名的导出,可以在需要时导入。

import React, {Component} from 'react`';

答案 2 :(得分:0)

导入hello from 'module',因为您默认将其导出。 导出可以命名为export(每个模块几个),默认导出(每个模块一个),已命名和默认的混合。 命名为

    export function square(x) {
      return x * x;
    }

    export function diag(x, y) {
      return sqrt(square(x) + square(y));
    }

    import { square, diag } from '---';

在默认导出中,我们写成export default function(){},在文件中只有一个导出时使用。请注意,该函数没有名称。

    //------ myFunc.js ------
    export default function () { ... };

    //------ main1.js ------
    import myFunc from 'myFunc';
    myFunc();

此处的备忘单:https://hackernoon.com/import-export-default-require-commandjs-javascript-nodejs-es6-vs-cheatsheet-different-tutorial-example-5a321738b50f

答案 3 :(得分:0)

默认只能导出一个变量或函数或任何内容。那么您可以将其导入到任何位置。

export default function hello(){
    return "Hello";
}

或在文件的最后导出函数。

function hello(){
    return "Hello";
}

export default hello;

然后,您可以导入为

import hello from '../module.js'
相关问题