首页 > 解决方案 > SyntaxError: Unexpected token { 同时从文件导入函数

问题描述

我正在尝试创建自己的库来获取天气预报,问题是我在导入函数时遇到问题

我已经尝试过了export function convertDate ...,但没有成功

这是我得到的错误:

(function (exports, require, module, __filename, __dirname) { import {convertDate} from "./utils/DataManagement";
                                                                     ^

SyntaxError: Unexpected token {
    at new Script (vm.js:84:7)
    at createScript (vm.js:264:10)
    at Object.runInThisContext (vm.js:312:10)
    at Module._compile (internal/modules/cjs/loader.js:696:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:747:10)
    at Module.load (internal/modules/cjs/loader.js:628:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:568:12)
    at Function.Module._load (internal/modules/cjs/loader.js:560:3)
    at Module.require (internal/modules/cjs/loader.js:665:17)
    at require (internal/modules/cjs/helpers.js:20:18)

这是我导入函数的方式:

import {convertDate} from "./utils/DataManagement";

最后,这里是我拥有函数本身的地方,也是我导出它的地方:

function convertDate(date) {
    let newDate = new Date(date.getTime() + date.getTimezoneOffset() * 60 * 1000);
    let offs = date.getTimezoneOffset() / 60;
    let hours = date.getHours();
    newDate.setHours(hours - offs);
    return newDate;
}

export { convertDate };

标签: javascriptnode.jsexport

解决方案


您需要使用 ES6 编译器来使用导入/导出

没有它你应该使用 ES5 module.exports

这是一个资源资源


推荐阅读