Node.js - SyntaxError: 意外的记号'import'

24 浏览
0 Comments

Node.js - SyntaxError: 意外的记号'import'

我不明白发生了什么问题。

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

admin 更改状态以发布 2023年5月25日
0
0 Comments

不幸的是,Node.js 尚不支持 ES6 的 import

为了实现您所尝试的操作(导入 Express 模块),这段代码应该足够了

var express = require("express");

此外,确保通过运行进行了 Express 的安装

$ npm install express

有关学习 Node.js 的更多信息,请参阅 Node.js Docs

0
0 Comments

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

Node 12Node 12 开始,你可以使用 .mjs 扩展名,或在 package.json 中设置 "type": "module"。你需要使用 --experimental-modules 标志运行 node。

Node 9Node 9 中,它在标志后启用,并使用 .mjs 扩展名。

node --experimental-modules my-app.mjs


虽然 import 确实是 ES6 的一部分,但不幸的是,在 NodeJS 中还没有默认支持它,而且只有最近才在浏览器中支持。

请参见 MDN 上的 浏览器兼容性表格这个 Node 问题

来自 James M Snell 的文章 Update on ES6 Modules in Node.js(2017 年 2 月):

正在进行工作,但这需要一些时间 - 我们目前至少要花费一年的时间。

在支持原生导入语句出现之前(在 Node 13+ 中已标记为稳定),你必须继续使用经典的 require 语句

const express = require("express");

如果你真的想在 NodeJS 中使用新的 ES6/7 功能,可以使用 Babel 进行编译。这里有一个示例服务器

0