Error module is not defined

So i have been trying to run this web app and at first it showed (node:12960) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension....

So i have been trying to run this web app and at first it showed

(node:12960) Warning: To load an ES module, set «type»: «module» in the package.json or use the .mjs extension.
C:UsersJreact-messengerstream-chat-boilerplate-apisrcindex.js:1
import dotenv from ‘dotenv’;
^^^^^^

SyntaxError: Cannot use import statement outside a module

And then i went to put set the type: module in the package.json but it gave me this error

ReferenceError: module is not defined

at file:///C:/Users/J/react-messenger/stream-chat-boilerplate-api/src/index.js:38:1

Here is my code:

import dotenv from 'dotenv';
dotenv.config();

import fs from 'fs';
import path from 'path';
import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
import helmet from 'helmet';
import compression from 'compression';

const api = express();

api.use(cors());
api.use(compression());
api.use(helmet());
api.use(bodyParser.urlencoded({ extended: true }));
api.use(bodyParser.json());

api.listen(process.env.PORT, error => {
    if (error) {
        console.warn(error);
        process.exit(1);
    }

    // eslint-disable-next-line array-callback-return
    fs.readdirSync(path.join(__dirname, 'routes')).map(file => {
        require('./routes/' + file)(api);
    });

    console.info(
        `Running on port ${process.env.PORT} in ${
            process.env.NODE_ENV
        } mode. 🚀`
    );
});

module.exports = api;

I dont know what am doing wrong

Error:

npm run test:e2e

> react-labs-app@0.1.0 test:e2e D:projectsreact-labs-app
> cd e2e && jest

ReferenceError: module is not defined
    at file:///D:/projects/react-labs-app/e2e/jest.config.js:1:1
    at ModuleJob.run (internal/modules/esm/module_job.js:152:23)
    at async Loader.import (internal/modules/esm/loader.js:166:24)
    at async readConfigFileAndSetRootDir (D:projectsreact-labs-appnode_modulesjestnode_modulesjest-configbuildreadConfigFileAndSetRootDir.js:126:32)
    at async readConfig (D:projectsreact-labs-appnode_modulesjestnode_modulesjest-configbuildindex.js:217:18)
    at async readConfigs (D:projectsreact-labs-appnode_modulesjestnode_modulesjest-configbuildindex.js:406:26)
    at async runCLI (D:projectsreact-labs-appnode_modulesjestnode_modules@jestcorebuildcliindex.js:230:59)
    at async Object.run (D:projectsreact-labs-appnode_modulesjestnode_modulesjest-clibuildcliindex.js:163:37)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! react-labs-app@0.1.0 test:e2e: `cd e2e && jest`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the react-labs-app@0.1.0 test:e2e script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:UsersSpartaAppDataRoamingnpm-cache_logs2021-01-11T16_39_52_806Z-debug.log

Весь код на ветке e2e-tests: https://github.com/daniilgri/react-labs-app/tree/e…
Скрипт запуска «test:e2e»: «cd e2e && jest»
e2e папка лежит наровне с package.json, в ней конфиг jest и jest-puppeteer.

jest-puppeteer.config.js

module.exports = {
  launch: {
    headless: false,
    slowMo: 300,
  },
};

jest.config.js

module.exports = {
  preset: "jest-puppeteer",
  globals: {
    URL: "http://localhost:3000",
  },
};

This is a line that I do not want to see anymore. It happened to me when I tried to set up testing an angular application with some directives, using karma. I thought that I had followed all the steps to set it all up correctly, but I kept on getting this line, indicating that something was indeed wrong. I finally got it all to work, and to prevent others (and myself) the hassle again of finding out what you have to do to get karma working correctly (especially when you already have some js files that you would like to test), I will outline here shortly what I did.

Being a good GDD developer (guilt driven developer for first writing code and then starting to add test code) I already had some files with code and now it was time to add some tests for it. I installed karma, answered the required questions for creating a config file and started karma. Failure:

Uncaught ReferenceError: angular is not defined

First failure was that the source files that you own code depends on, should be described in the correct order in your karma.conf.js file. So the base looked like this:

// list of files / patterns to load in the browser
files: [
  "bower_components/**/*.js", "js/**/*.js", "app/**/*.js", "**/*.spec.js"
]

This resulted in everything being loaded, but not in the correct order. This particular annoyance had already bitten me before, so after changing my files list to the correct order, I got a bit further. The lines now looked like:

// list of files / patterns to load in the browser
files: [
  "bower_components/jquery/jquery.js",
  "bower_components/angular/angular.js",
  "bower_components/angular-route/angular-route.js",
  "bower_components/angular-bootstrap/ui-bootstrap.js",
  "bower_components/elastic.js/dist/elastic.js",
  "bower_components/elastic.js/dist/elastic-angular-client.js",
  "app/js/**/*.js",
  "app/js/general/directives.js",
  "app/searchbooks/**/*.js",
  "test/**/*Spec.js"
]

Step further, but now the module is not defined error showed up. The directive that I wanted to test, had a dependency on angular (obviously) and this was defined in the beforeEach step:

describe('button directive', function () {
    var $compile, $rootScope;
    beforeEach(module('directives.button'));
    beforeEach(inject(function (_$compile_, _$rootScope_) {
        $compile = _$compile_;
        $rootScope = _$rootScope_;
    }));

...

Since the error was indicating that module could not be defined, I changed the beforeEach line to

beforeEach(angular.module('directives.button'));

And now that particular error was gone, but another error popped up about the inspect not being found. So I added the angular keyword also in front of the inject function, but this didn’t work out either.

Well, after a lot of trials and errors, I found out that I had to include the test/lib/angular-mocks.js file in the dependencies as well. That solved it, since module could now be found as this is defined in the angular-mocks.js.

Also make sure that you do not include the angular-scenario.js file in the dependencies as well, since then it will not run any of the karma tests anymore. Hope this helps someone else as well.

Update
Today I spent again a lot of time trying to get a test to work with angular and again the problem was between the keyboard and the back of my chair. What I had done was trying to test a controller with some services that this controller depended on. I had defined everything correctly and the sources were running merily and happily on my webapplication, yet whatever test I tried to run it always showed me the error: Unknown provider: ordersServiceProvider <- ordersService
But this was all running correctly as web application. Fast forward some 2 hours of refactoring, re-testing, swearing, scratching of head and lo and behold, finally I noticed the culprit. In my test I had

var moduleToTest = angular.module("orders")

But this means that the real deal, the real angular gets loaded and not the mock. Sigh, removing the angular. fixed this issue. You might have thought that after the previous error with the mocks on angular that I would be more suspicious but alas, I made almost the same error again.

Ah Okay, I see my mistake, thanks. Tried it out with running MagicMirror2 and there was no error in the log. But somehow it still won´t turn off my monitor.

Maybe you have an answer, Here is the full config.
The last two rows in the console log where from my voice command, so I guess it works but don´t know why the Monitor is not responding.

** full MagicMirror config:**

/* Magic Mirror Config Sample
 *
 * By Michael Teeuw http://michaelteeuw.nl
 * MIT Licensed.
 *
 * For more information how you can configurate this file
 * See https://github.com/MichMich/MagicMirror#configuration
 *
 */

var config = {
	address: "localhost", // Address to listen on, can be:
	                      // - "localhost", "127.0.0.1", "::1" to listen on loopback interface
	                      // - another specific IPv4/6 to listen on a specific interface
	                      // - "", "0.0.0.0", "::" to listen on any interface
	                      // Default, when address config is left out, is "localhost"
	port: 8080,
	ipWhitelist: ["127.0.0.1", "::ffff:127.0.0.1", "::1"], // Set [] to allow all IP addresses
	                                                       // or add a specific IPv4 of 192.168.1.5 :
	                                                       // ["127.0.0.1", "::ffff:127.0.0.1", "::1", "::ffff:192.168.1.5"],
	                                                       // or IPv4 range of 192.168.3.0 --> 192.168.3.15 use CIDR format :
	                                                       // ["127.0.0.1", "::ffff:127.0.0.1", "::1", "::ffff:192.168.3.0/28"],

	language: "de",
	timeFormat: 24,
	units: "metric",

	modules: [
		{
    			module: 'MMM-AlexaOnOff',
    			config: {
      		 		 devices: [{ 
             				 name: "Magic Mirror",
		
              			on: { 
                			notification: "MMM-AlexaOnOff_ACTION_RECEIVED",
                			payload: { actionName:'monitorOn' }
             				},
             			off: { 
                			notification: "MMM-AlexaOnOff_ACTION_RECEIVED",
                			payload: { actionName:'monitorOff' }
              				},
       				 }]
    			}
		},

		{
			module: "alert",
		},

		{
			module: "updatenotification",
			position: "top_bar"
		},
		{
			module: "clock",
			position: "top_left"
		},
		{
			module: "MMM-Fuel",
			position: "top_left",
	  	        config: {
					api_key: " //my key",
					lat: //cordinates,
					lng: //cordinates,
					types: ["e5"],
					radius: 2.5
			}		
			
		},
/*		{
*			module: "calendar",
*			header: "Kalender",
*			position: "top_left",
*	  	        config: {
*				calendars: [
*					{
*						symbol: "calendar-check-o ",
*						url: "https://calendar.google.com/calendar/ical/de.german%23holiday%40group.v.calendar.google.com/public/basic.ics"
*					}
*				]
*			}
*		},
*/
	
		{
			module: "compliments",
			position: "lower_third"
		},
		{
			module: "currentweather",
			position: "top_right",
			config: {
				location: "Aschaffenburg,DE",
				locationID: "",  //ID from http://bulk.openweathermap.org/sample/; unzip the gz file and find your city
				appid: "//my ID"
			}
		},
		{
			module: "weatherforecast",
			position: "top_right",
			header: "Wetterbereicht",
			config: {
				location: "Aschaffenburg,DE",
				locationID: "",  //ID from http://www.openweathermap.org/help/city_list.txt
				appid: "//myID"
			}
		},
		{
			module: "newsfeed",
			position: "bottom_bar",
			config: {
				feeds: [
					{
						title: "Nachrichten",
						url: "http://www.tagesschau.de/xml/rss2"
					}
				],
				showSourceTitle: true,
				showPublishDate: true
			}
		},
	]

};

/*************** DO NOT EDIT THE LINE BELOW ***************/
if (typeof module !== "undefined") {module.exports = config;}

full config fauxmojs:

'use strict';

const FauxMo = require('fauxmojs');

let fauxMo = new FauxMo(
  {
    ipAddress: '//myIP',
    devices: [
           {
        name: 'Magic Mirror',
        port: 11001,
        handler: (action) => {
          console.log('Magic Mirror action:', action);
        }
      }
    ]
  });

console.log('started..');

console log:

pi@raspberrypi:~/MagicMirror $ npm start

> magicmirror@2.5.0 start /home/pi/MagicMirror
> sh run-start.sh

Starting MagicMirror: v2.5.0
Loading config ...
Loading module helpers ...
Initializing new module helper ...
Module helper loaded: MMM-AlexaOnOff
No helper found for module: alert.
Initializing new module helper ...
Module helper loaded: updatenotification
No helper found for module: clock.
Initializing new module helper ...
Module helper loaded: MMM-Fuel
No helper found for module: compliments.
No helper found for module: currentweather.
No helper found for module: weatherforecast.
Initializing new module helper ...
Module helper loaded: newsfeed
All module helpers loaded.
Starting server on port 8080 ... 
Server started ...
Connecting socket for: MMM-AlexaOnOff
Module helper started for MMM-AlexaOnOff
Connecting socket for: updatenotification
Connecting socket for: MMM-Fuel
Starting module helper: MMM-Fuel
Connecting socket for: newsfeed
Starting module: newsfeed
Sockets connected & modules started ...
Launching application.
FauxMo service started. Listening on _my IP Adress_:11001
Create new news fetcher for url: http://www.tagesschau.de/xml/rss2 - Interval: 300000
Fauxmo Action for Magic Mirror: off
Fauxmo Action for Magic Mirror: on

#javascript #webpack #es6-modules

Вопрос:

Я разрабатываю конкретный пакет npm, в котором я хочу иметь возможность импортировать различные помощники из базового пакета в синтаксисе ESM, например,

 import {
   myFunction,
   myConstant
} from 'my-npm-package-library'
 

Это мой файл entrypoint index.ts:

 // Interface CelestiaSkyViewerOptions:
export interface CelestiaSkyViewerOptions {
  fullscreen?: boolean
  showSolar?: boolean
  showEcliptic?: boolean
  showAsterisms?: boolean
  showStars?: boolean
  showConstellations?: boolean
  showConstellationBoundaries?: boolean
  showCardinalPoints?: boolean
  showTimeAndCoordinateLocation?: boolean
  showAstronomicalTime?: boolean
  showCopyright?: boolean
}

// Export all default components:
export { default as CelestiaAstronomicalEpoch } from '@/components/CelestiaAstronomicalEpoch/CelestiaAstronomicalEpoch.vue'

export { default as CelestiaCopyright } from '@/components/CelestiaCopyright/CelestiaCopyright.vue'

export { default as CelestiaIAUStarKey } from '@/components/CelestiaIAUKeys/CelestiaIAUStarKey.vue'

export { default as CelestiaObserverLocale } from '@/components/CelestiaObserverLocale/CelestiaObserverLocale.vue'

export { default as CelestiaOrientationCompass } from '@/components/CelestiaOrientationCompass/CelestiaOrientationCompass.vue'

export { default as CelestiaOrientationPermission } from '@/components/CelestiaOrientationPermission/CelestiaOrientationPermission.vue'

export { default as CelestiaSkyViewer } from '@/components/CelestiaSkyViewer/CelestiaSkyViewer.vue'

export {
  annotateBody,
  drawBody,
  drawClosedPath,
  drawEllipticalGalaxy,
  drawLine,
  drawMoon,
  drawSun,
  drawText,
  highlightBody,
  resetPath
} from '@/composables/canvas'

export { azimuthalOffset } from '@/composables/celestia'

export { bayerStarsFilter, iauStarsFilter } from '@/composables/filters'

export {
  cardinals,
  coords,
  latitude,
  locatedAt,
  longitude,
  onEquatorialPositionChange,
  position,
  useObserversLocation,
  validateLatitude,
  validateLongitude
} from '@/composables/geolocation'

export { datetime } from '@/composables/globals'

export {
  deviceOrientationPermissionDialogOpen,
  deviceOrientationPermissionState,
  isOrientationCompassOpen,
  orientationCompassHeading,
  useDeviceMotionPermission,
  useDeviceOrientationPermission
} from '@/composables/orientation'
 

Однако при попытке зафиксировать этот код линтер при фиксации, который у меня есть, выдает следующую ошибку:

 ReferenceError: module is not defined in ES module scope
 

Я пытался обойти эту конкретную ошибку в Google, но, похоже, никто не хочет играть в мяч с линтером…

Полная трассировка стека для любых любителей мусора:

 ERROR  ReferenceError: module is not defined in ES module scope
        This file is being treated as an ES module because it has a '.js' file extension and '/Users/michael/observerly/celestia-vue/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
ReferenceError: module is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and '/Users/michael/observerly/celestia-vue/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
 

Комментарии:

1. Это не похоже на ошибку линтера (сообщение), а скорее на ошибку во время выполнения. Где именно возникает эта ошибка? Поскольку ни один из опубликованных вами кодов не ссылается module на него, он определенно не брошен туда.

2. @FelixKling Привет, Феликс, спасибо за твой комментарий. Он выбрасывается при запуске npm run lint ->, который, в свою очередь, вызывает vue-cli-service lint… Я добавлю к вопросу полную цепочку ошибок.

3. @FelixKling, я чувствую, что это может быть полезно: cli.vuejs.org/guide/build-targets.html#library

4. Или даже цели сборки веб-пакетов?

5. Похоже, что удаление type: module из моего пакета.json устранило ошибку…

Понравилась статья? Поделить с друзьями:
  • Error mods were not processed as server update had errors
  • Error modifying перевод
  • Error modifying c gog games the witcher 3 wild hunt goty content metadata store
  • Error modifying c games cyberpunk 2077 archive pc content audio 1 general archive
  • Error model is singular