javascript - ES6 import "module"不允许访问 "module"的函数

标签 javascript node.js import ecmascript-6

我正在尝试将 ES6 imorts 与 babel 和 Node.js 一起使用

import "./utils.js";

log("something"); //throw an error : log is not defined

我的 utils.js 看起来像这样:

function log(... params){
    console.log(... params);
}

log("module utils executed");
//Is executed and display "module utils executed" in the console.

我还尝试使用导出函数 log(... params)导出默认日志(... params) 但它不起作用。

所以我不明白这是如何工作的......

编辑:

我知道另一种导入方式是import utils from "./utils.js"

但这不是我想要的。我希望能够使用 log() 而不用模块变量名作为前缀。就像this blog post

最佳答案

ES6 import 和 Node.js require Question Describe The Difference

如果您将使用 Node.js require:

你的utils.js文件将是

function log(params) {
    console.log(params);
}

module.exports = {
   log
};

另一个文件将导入您的 Utils 模块

var utils = require('./utils');
utils.log("test");

如果您将使用 ES6 模块:

你的utils.js文件将是

var log = function (params) {
    console.log(params);
}

var utils = {
    log: log
}

export default utils;

另一个文件将导入您的 Utils 模块

import utils from 'utils';

utils.log("test");

更新

根据your Comment,是的,你可以这样做,但是使用ES6模块

你的utils.js文件将是

function log(params) {
    console.log(params);
}

function anotherLog(params) {
    console.log(params);
}

export { log, anotherLog }

另一个文件将导入您的 Utils 模块

import { log } from 'utils';

log("test");

关于javascript - ES6 import "module"不允许访问 "module"的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34955456/

相关文章:

bash - Node.js 执行程序 : best way of killing a child pipe and all of its children

c++ - 无法在 Windows 8 上包含带有 qt creator 的路径

具有循环导入的 Java 文件

javascript - 如何使用 JavaScript 'match' 查找字符的出现次数

javascript - 413 请求实体太大 HighCharts

javascript - 如何通过onclick传递字符串参数

javascript - 带有回调的 Bluebird promise 生成器

javascript - 使用 node.js 连接到 ravendb

java - 类路径中带有属性文件的外部库的导入未解决

javascript - yepnope & jquery & modernizr 初学者问题