Node.js - SyntaxError:意外的令牌导入 [英] Node.js - SyntaxError: Unexpected token import

查看:29
本文介绍了Node.js - SyntaxError:意外的令牌导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白出了什么问题.节点 v5.6.0NPM v3.10.6

I don't understand what is wrong. Node v5.6.0 NPM v3.10.6

代码:

function (exports, require, module, __filename, __dirname) {
    import express from 'express'
};

错误:

SyntaxError: Unexpected token import
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:387:25)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Function.Module.runMain (module.js:447:10)
    at startup (node.js:140:18)
    at node.js:1001:3

推荐答案

Node 13+节点 13,你可以使用 .mjs 扩展名,或者设置 {"type":"module"} 在你的 package.json 中.您不需要使用 --experimental-modules 标志.模块现在在 node.js 中被标记为稳定

Node 13+ Since Node 13, you can use either the .mjs extension, or set {"type": "module"} in your package.json. You don't need to use the --experimental-modules flag. Modules is now marked as stable in node.js

节点 12 由于 节点 12,您可以使用任一.mjs 扩展名,或在 package.json 中设置 type": module".您需要使用 --experimental-modules 标志运行节点.

Node 12 Since Node 12, you can use either the .mjs extension, or set "type": "module" in your package.json. And you need to run node with the --experimental-modules flag.

节点 9节点 9,它在标志后面启用,并使用 .mjs 扩展名.

Node 9 In Node 9, it is enabled behind a flag, and uses the .mjs extension.

node --experimental-modules my-app.mjs


虽然 import 确实是 ES6 的一部分,但 遗憾的是,NodeJS 默认还不支持它,并且只是最近才在浏览器中获得支持.


While import is indeed part of ES6, it is unfortunately not yet supported in NodeJS by default, and has only very recently landed support in browsers.

请参阅 浏览器兼容表在 MDN这个节点问题.

来自 James M Snell 的 Node.js 中 ES6 模块的更新(2017 年 2 月):

From James M Snell's Update on ES6 Modules in Node.js (February 2017):

工作正在进行中,但需要一些时间 — 我们目前正在考虑至少一年左右.

Work is in progress but it is going to take some time — We’re currently looking at around a year at least.

直到原生支持(现在在 Node 13+ 中标记为稳定),你必须继续使用经典的require语句:

Until support shows up natively (now marked stable in Node 13+), you'll have to continue using classic require statements:

const express = require("express");

如果你真的想在 NodeJS 中使用新的 ES6/7 特性,你可以使用 Babel 编译它.这是一个示例服务器.

If you really want to use new ES6/7 features in NodeJS, you can compile it using Babel. Here's an example server.

这篇关于Node.js - SyntaxError:意外的令牌导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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