导入不适用于Node.js版本11.8.0 [英] Import not working on Node.js version 11.8.0

查看:147
本文介绍了导入不适用于Node.js版本11.8.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个简单的程序,该程序使用充满字典单词的对象.我想从另一个文件中导入该对象,因为它很大.尝试导入它时,我收到一个错误,看起来像Node.js不知道它是什么.

I am writing a simple program that uses a object full of dictionary words. I want to import that object from a different file as it is very large. When trying to import it I get an error that looks like Node.js doesn't know what it is.

我已经尝试过重新安装最新版本的Node.js.

I have already tried reinstalling the latest version of Node.js.

这是重要的代码:

import {dict} from './words_dictionary'

这就是全部:

import {dict} from './words_dictionary'


function exists(obj,str) {
  if(obj[str]) {
    return true
  } else {
    return false
  }
}
console.log(exists(dict, 'hello'))

这是字典代码的要旨:

export let dict = {a: 1, aa: 1, aaa: 1, aah: 1, aahed: 1, aahing: 1, aahs:
1, aal: 1, aalii: 1, aaliis: 1, aals: 1, aam: 1, aani: 1, aardvark: 1,
aardvarks: 1,...~3000 more}

我期望是真的,但是我遇到了这个错误:

I expected true, but I got this error:

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 Function.Module.runMain (internal/modules/cjs/loader.js:801:12)
at executeUserCode (internal/bootstrap/node.js:526:15)

ECMAScript  6现在可以正常工作,但是我现在收到未定义dict的错误.这可能与文件大小有关,因为我多次检查了拼写错误吗?

ECMAScript 6 is now working, but I am now getting the error of dict not being defined. Could this have something to do with the file size, because I have checked multiple times for spelling errors?

推荐答案

您是否能够在代码的其他位置使用import键盘?这里的问题可能是您没有将代码转换为ECMAScript  5.由于import是ECMAScript  6功能,因此Node.js尚未完全支持它.如果您使用Babel这样的工具来转译您的代码,则可以解决此问题.如果您不想这样做,请尝试使用require.

Have you been able to use the import keyboard elsewhere in your code? The issue here may be that you aren't transpiling your code into ECMAScript 5. Since import is an ECMAScript 6 feature, it hasn't yet been fully supported by Node.js. If you use a tool like Babel to transpile your code, you may fix this issue. If you don't want to do this, try using require instead.

如前所述,在Node.js 9+中,您也可以在启用了--experimental-modules标志的.mjs文件中使用它.

As noted, in Node.js 9+ you can also use it in .mjs files with the --experimental-modules flag enabled.

node --experimental-modules file.mjs

Node.js import兼容性

这篇关于导入不适用于Node.js版本11.8.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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