简体   繁体   中英

Node - Protractor "SyntaxError: Cannot use import statement outside a module" when switching to ES6 modules

To run my tests I use

protractor conf.js

I get

File 'main' needs function 'httpGet' from file 'support.js'

In 'main' I changed from

const { httpGet } = require('./support');

to

import { httpGet } from './support';

and in the support file from

exports.httpGet = (siteUrl) => {

to

export function httpGet(siteUrl) {

but I get

import { httpGet } from ('./support');
^^^^^^

SyntaxError: Cannot use import statement outside a module

I tried using .mjs extensions, adding "type": "module" in my package.json file but they all give the same error. Where do I put the import? I currently have it within a specific it example, is that ok?'

Note that I don't run the node command directly, i use

protractor conf.js

Update 3: 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.

Update 2: 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.

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

node --experimental-modules my-app.mjs

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.

If you really want to use new ES6/7 features in NodeJS, you can compile it using Babel.

Node.js has included experimental support for ES6 support. Read more about here: https://nodejs.org/docs/latest-v12.x/api/esm.html#esm_enabling Node >= v13

Save the file with .mjs extension, or Add type as module in the nearest package.json. Node < v12

Save the file with ES6 modules with .mjs extension and run it like: node --experimental-modules my-app.mjs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM