我不明白是怎么回事。 节点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

当前回答

如果你仍然不能使用“import”,下面是我处理它的方法: 只需将其转换为节点友好的要求。例子:

import { parse } from 'node-html-parser';

等于:

const parse = require('node-html-parser').parse;

其他回答

我一直想把它修好。以下是有效的方法:

使用最新的节点版本。我使用的是v14.15.5。运行:node——version来验证你的版本 命名文件,使它们都以.mjs而不是.js结尾


例子:

mod.mjs

export const STR = 'Hello World'

test.mjs

import {STR} from './mod.mjs'
console.log(STR)

执行命令node test.mjs

你应该看到“Hello World”。

错误:SyntaxError:未预期的令牌导入或SyntaxError:未预期的令牌导出


解决方案:以更改所有导入为例

const express               = require('express');
const webpack               = require('webpack');
const path                  = require('path');
const config                = require('../webpack.config.dev');
const open                  = require('open');

同时修改export default = foo;模块。出口= foo;

如果你仍然不能使用“import”,下面是我处理它的方法: 只需将其转换为节点友好的要求。例子:

import { parse } from 'node-html-parser';

等于:

const parse = require('node-html-parser').parse;

只需安装更高版本的Node。直到Node v10 es6不支持。您需要禁用一些标志或使用

My project uses node v10.21.0, which still does not support ES6 import keyword. There are multiple ways to make node recognize import, one of them is to start node with node --experimental-modules index.mjs (The mjs extension is already covered in one of the answers here). But, this way, you will not be able to use node specific keyword like require in your code. If there is need to use both nodejs's require keyword along with ES6's import, then the way out is to use the esm npm package. After adding esm package as a dependency, node needs to be started with a special configuration like: node -r esm index.js