Node can't find module in local file even though path is correct - javascript

I have encountered a problem while writing an API in Node and Express. I have a main router file inside folder 'shared' that I'm using to import other routers. I created a folder called 'module' inside 'src' folder, and inside it I created a 'products' folder. Inside the products folder, there's a folder called 'routes', with a file called 'productRoutes', which is where I declare all routes related to products. I'm trying to import the products router inside the main router file, which is outside the modules folder, but I keep getting the error:
"Error: Cannot find module 'src/modules/products/routes/productRoutes'",
even though the path to the file is correct.
This is the folder structure of my project:
So basically I'm trying to import file in 'src/modules/products/routes/productRoutes' into 'src/shared/http/routes/index', but I get the following error:
Error: Cannot find module 'src/modules/products/routes/productRoutes'
Require stack:
- C:\Users\joaog\Desktop\Projetos\api-sales\src\shared\http\routes\index.ts
- C:\Users\joaog\Desktop\Projetos\api-sales\src\server.ts
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:995:15)
at Function.Module._load (node:internal/modules/cjs/loader:841:27)
at Module.require (node:internal/modules/cjs/loader:1061:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (C:\Users\joaog\Desktop\Projetos\api-sales\src\shared\http\routes\index.ts:2:1)
at Module._compile (node:internal/modules/cjs/loader:1159:14)
at Module._compile (C:\Users\joaog\Desktop\Projetos\api-sales\node_modules\source-map-support\source-map-support.js:568:25)
at Module.m._compile (C:\Users\joaog\AppData\Local\Temp\ts-node-dev-hook-7670897674579045.js:69:33)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at require.extensions..jsx.require.extensions..js (C:\Users\joaog\AppData\Local\Temp\ts-node-dev-hook-7670897674579045.js:114:20)
[ERROR] 22:49:49 Error: Cannot find module 'src/modules/products/routes/productRoutes'
Require stack:
- C:\Users\joaog\Desktop\Projetos\api-sales\src\shared\http\routes\index.ts
- C:\Users\joaog\Desktop\Projetos\api-sales\src\server.ts
This is the code in the main routes file in which I'm importing the file from modules folder:
import {Request, Response, Router} from 'express';
import productsRouter from 'src/modules/products/routes/productRoutes';
const routes = Router();
routes.use('/products',productsRouter);
routes.get('/',(req : Request,res : Response)=>{
return res.json({message : "hello world!"});
})
export default routes;
this is the products router file:
import { Router } from "express";
import ProductsController from "src/modules/products/controllers/ProductsController";
const productsRouter = Router();
const productsController = new ProductsController();
productsRouter.get('/',productsController.index);
productsRouter.get('/:id',productsController.show);
productsRouter.post('/',productsController.create);
productsRouter.put('/:id',productsController.update);
productsRouter.delete('/:id',productsController.delete);
export default productsRouter;
and this is the package.json file:
{
"name": "api-sales",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "ts-node-dev --inspect --transpile-only --ignore-watch node_modules src/server.ts",
"lint": "eslint . --ext .ts",
"lint-fix": "eslint . --ext .ts --fix",
"typeorm" : "ts-node-dev node_modules\\typeorm\\cli.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#types/cors": "^2.8.13",
"#types/express": "^4.17.17",
"#types/node": "^18.13.0",
"#typescript-eslint/eslint-plugin": "^5.51.0",
"#typescript-eslint/parser": "^5.51.0",
"eslint": "^8.34.0",
"eslint-config-prettier": "^8.6.0",
"eslint-plugin-prettier": "^4.2.1",
"ts-node-dev": "^2.0.0",
"typescript": "^4.9.5"
},
"dependencies": {
"cors": "^2.8.5",
"express": "^4.18.2",
"express-async-errors": "^3.1.1",
"pg": "^8.9.0",
"reflect-metadata": "^0.1.13",
"typeorm": "^0.2.29"
}
}
I created a dummy file inside 'modules' folder and tried to import it in main routes file in 'shared' folder and got the same error, but then I tried to import the dummy file into 'src/server' and every thing worked fine. So it appears that i can't import any files from 'modules' into 'shared'. I also tried using require instead of import but ended up with same error.

Related

Unable to run JEST test

I'm facing an issue when I try to import something using require() function in jest test file.
script2.test.js
const fetch = require('node-fetch');
it('test function', () => {
expect(4).toEqual(4);
});
Package.json
{
"name": "jest-test",
"version": "1.0.0",
"description": "",
"type": "module",
"scripts": {
"test": "jest --watchAll"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/cli": "^7.15.7",
"#babel/core": "^7.15.8",
"#babel/plugin-transform-async-to-generator": "^7.14.5",
"#babel/preset-env": "^7.15.8",
"jest": "^27.3.1"
},
"dependencies": {
"node-fetch": "^3.0.0"
},
"jest": {
"transform": {
"^.+\\.(js|jsx)$": "babel-jest"
}
}
}
babel.config.cjs
module.exports = {presets: ['#babel/preset-env']}
I'm getting following errors when I run the test using npm test
FAIL ./script2.test.js
● Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
Details:
C:\work\jest-udemy\node_modules\node-fetch\src\index.js:9
import http from 'http';
^^^^^^
SyntaxError: Cannot use import statement outside a module
> 1 | const fetch = require('node-fetch');
| ^
I'm new to JEST, any help is much appreciated.
My Node version is 14.17.3
Thanks you.
It seems that one still needs to jump through the hoops to make jest work with ESM.
In package.json change your script to:
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js --watchAll"
And in script2.test.js use import:
import fetch from 'node-fetch';
P.S. This was tested with node 14.15.1

how to require constants which is exported in ES6 module?

The original variables are exported in ES6 module like this:
export const url = 'https://example.com/api'
I know I can use this variable using
import {url} from 'src/api'
But the thing is I can't use import in gatsby-config.js file and only can use ES5 syntax.
I tried like this:
const {url} = require('src/api')
but it doesn't work and get errors while gatsby develop
The error is following:
export const url = 'https://example.com/api'
^^^^^^
SyntaxError: Unexpected token 'export'
- v8-compile-cache.js:226 NativeCompileCache._moduleCompile
[project]/[v8-compile-cache]/v8-compile-cache.js:226:18
- v8-compile-cache.js:172 Module._compile
[project]/[v8-compile-cache]/v8-compile-cache.js:172:36
- loader.js:995 Object.Module._extensions..js
internal/modules/cjs/loader.js:995:10
- loader.js:815 Module.load
internal/modules/cjs/loader.js:815:32
- loader.js:727 Function.Module._load
internal/modules/cjs/loader.js:727:14
- loader.js:852 Module.require
internal/modules/cjs/loader.js:852:19
- v8-compile-cache.js:159 require
[project]/[v8-compile-cache]/v8-compile-cache.js:159:20
- gatsby-config.js:4 Object.<anonymous>
C:/project/gatsby-config.js:4:26
- v8-compile-cache.js:178 Module._compile
[project]/[v8-compile-cache]/v8-compile-cache.js:178:30
- loader.js:995 Object.Module._extensions..js
internal/modules/cjs/loader.js:995:10
- loader.js:815 Module.load
internal/modules/cjs/loader.js:815:32
- loader.js:727 Function.Module._load
internal/modules/cjs/loader.js:727:14
- loader.js:852 Module.require
internal/modules/cjs/loader.js:852:19
- v8-compile-cache.js:159 require
[project]/[v8-compile-cache]/v8-compile-cache.js:159:20
- get-config-file.js:33 getConfigFile
[project]/[gatsby]/dist/bootstrap/get-config-file.js:33:20
When you exporting your constant if you use module.exports it should not give this error. Do it like this:
const yourUrl = 'https://example.com/api'
module.exports = { url: yourUrl }
Hope you know what you are trying to achieve because the result produces anti pattern against gatsbyjs specification as it already converts code internally from es6 to es5 after reading and validating gatsby-config.js.
So, try this way to require constants in gatsby-config.js which were exported in es6 module
From es6 to es5 conversion, install #babel/cli and #babel/core package i.e npm install #babel/cli #babel/core --save-dev
Add new npm/yarn script in package.json -> scripts -> "prepare_config" : "NODE_ENV=test babel ./gatsby-config.js <LIST_OF_FILES_TO_CONVERT> --out-dir ./"
Make sure babel-preset-gatsby directory is present under node_modules if not then install it i.e. npm install babel-preset-gatsby --save-dev
Either add .babelrc in project root directory having below code for babel preset and conversion.
{
"presets": [
[
"babel-preset-gatsby",
{
"forceAllTransforms": true,
"useBuiltIns": "usage"
}
]
]
}
OR if you don't want to add .babelrc then specify babel configuration in package.json.
"babel": {
"presets": [
[
"babel-preset-gatsby",
{
"forceAllTransforms": true,
"useBuiltIns": "usage"
}
]
]
}
Now run npm run prepare_config script first for conversion which will import required constants which were exported in ES6 module.
Then you can run gatsby develop successfully.
Change the type:"module" or set in package.json.
{
"name": "server",
"version": "1.0.0",
"type": "module",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo "Error: notestspecified" && exit 1",
"start": "nodemon server.js"
},
"keywords": [
],
"author": "",
"license": "ISC",
"dependencies": {
"#babel/core": "^7.16.5",
"body-parser": "^1.19.1",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.2",
"mongoose": "^6.1.3",
"nodemon": "^2.0.15"
}
}

Change 'import' to 'require', sucrase deployment

I'm trying to put my application into production. But, the teacher who was teaching put it for me, the lib 'sucrase' to use syntax of "import from" instead of "require". Only now Heroku is complaining that he doesn't understand the syntax "import". Is there anything I can do about line of code and configuration? Or do I have to change all "import from" to "require"? ... Lower the logs ...
logs in Heroku
2020-06-27T20:21:41.876688+00:00 app[web.1]: /app/src/server.js:1
2020-06-27T20:21:41.876689+00:00 app[web.1]: import app from './app';
2020-06-27T20:21:41.876690+00:00 app[web.1]: ^^^^^^
2020-06-27T20:21:41.876690+00:00 app[web.1]:
2020-06-27T20:21:41.876691+00:00 app[web.1]: SyntaxError: Cannot use import statement outside a module
2020-06-27T20:21:41.876691+00:00 app[web.1]: at wrapSafe (internal/modules/cjs/loader.js:1054:16)
2020-06-27T20:21:41.876692+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:1102:27)
My package.json
{
"name": "futs",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "nodemon src/server.js",
/ ^ ^ ^ Below at the code is a configuration about the 'nodemon' that the teacher gave me
"dev:debug": "nodemon --inspect src/server.js"
},
"dependencies": {
"aws-sdk": "^2.704.0",
"bcryptjs": "^2.4.3",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"date-fns": "^2.14.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"multer": "^1.4.2",
"multer-s3": "^2.9.0",
"nodemailer": "^6.4.10",
"pg": "^8.2.1",
"sequelize": "^5.21.13",
"sequelize-cli": "^5.5.1",
"uuid": "^8.1.0",
"yup": "^0.29.1"
},
"devDependencies": {
"eslint": "^6.8.0",
"eslint-config-airbnb-base": "^14.1.0",
"eslint-config-prettier": "^6.11.0",
"eslint-plugin-import": "^2.20.2",
"eslint-plugin-prettier": "^3.1.3",
"nodemon": "^2.0.4",
"prettier": "^2.0.5",
"sucrase": "^3.15.0"
}
}
nodemon.json
{
"execMap":{
"js": "node -r sucrase/register"
}
}
I don't know how to run to deploy, if anyone can help me
As you see in the error log : Cannot use import statement outside a module.
import statements are permitted only in ES modules not CommonJS see more about that here :
However you can make Node treat your file as a ES module you need to :
add "type": "module" to package.json .
Add --experimental-modules flag upon running your app(not necessary with Node 13.2.0+ so check your node version with node --version)
as follow :
// package.json
{
"type": "module"
}
take a look here for more information .
OR :
Alternatively you can use the .mjs instead of .jsextension .
SOURCES :
SyntaxError: Cannot use import statement outside a module
https://nodejs.org/api/esm.html .
https://nodejs.org/api/esm.html#esm_enabling .
https://nodejs.org/api/esm.html#esm_code_import_code_statements
To build my app using sucrase I use:
sucrase ./src -d ./dist --transforms imports
This is my package.json file:
"scripts": {
"dev": "nodemon src/server.js",
"build": "sucrase ./src -d ./dist --transforms imports",
"start": "node dist/server.js"
},

Debugger cannot find module 'StyleSheet'. My app runs fine. Path points fine

Very strange error that I cannot seem to solve.
React-native and node.js and VS Code
To get VS Code to get this far I used the line, yarn add babel-cli
Error I'm Getting:
Debugger listening on ws://127.0.0.1:39061/61f6ad51-d255-463a-a0ad-b686be9b8b0d
Object {dataReducer: Object, reducerSPY: Object, userApp: Object}
home.js:31
Error: Cannot find module 'StyleSheet'
module.js:555
at Function.Module._resolveFilename (module.js:555:15)
at Function.Module._load (module.js:482:25)
at Module.require (module.js:604:17)
at require (internal/module.js:11:18)
at Object.get StyleSheet [as StyleSheet] (c:\AndroidEverything\AndroidStudioProjects\Property2\AwesomeProject\node_modules\react-native\Libraries\react-native\react-native-implementation.js:98:29)
at Object.<anonymous> (c:/AndroidEverything/AndroidStudioProjects/Property2/AwesomeProject/app/components/home.js:195:16)
Strange because:
My app runs fine
If I comment out this line all other imports are found, just
StyleSheet.
All files are as I expected in its location. This seems buggy?
home.js(which is called by App.js)
import {
FlatList,
View,
Text,
ActivityIndicator,
StyleSheet
} from 'react-native';
launch.json
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}/App.js",
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/babel-node",
},
package.json
{
"name": "AwesomeProject",
"version": "0.1.0",
"private": true,
"devDependencies": {
"jest-expo": "25.0.0",
"react-native-scripts": "1.11.1",
"react-test-renderer": "16.2.0"
},
"main": "./node_modules/react-native-scripts/build/bin/crna-entry.js",
"scripts": {
"start": "react-native-scripts start",
"eject": "react-native-scripts eject",
"android": "react-native-scripts android",
"ios": "react-native-scripts ios",
"test": "node node_modules/jest/bin/jest.js"
},
"jest": {
"preset": "jest-expo"
},
"dependencies": {
"babel-cli": "^6.26.0",
"expo": "^25.0.0",
"react": "16.0.0",
"react-dom": "16.0.0",
"react-native": "0.52.0",
"react-navigation": "^1.5.1",
"react-redux": "^5.0.7",
"redux": "^3.7.2",
"redux-thunk": "^2.2.0",
"save": "^2.3.2"
}
}
Any ideas where to keep digging? launch.json file? connectivity? yarn? or a spelling error?
UPDATE:
Removed the line about babel since i'm using yarn for node.js and Expo to run on android. error has changed to:
path\Property2\AwesomeProject\App.js:1
(function (exports, require, module, __filename, __dirname) { import React,
{ Component } from 'react';
^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:152:10)
at Module._compile (module.js:624:28)
at Object.Module._extensions..js (module.js:671:10)
using yarn upgrade jest-expo#25.1.0-beta.0
warning "expo > react-native-maps#0.19.0" has incorrect peer dependency
"react-native#0.51.0".
warning " > react-native#0.52.0" has incorrect peer dependency
"react#16.2.0".
warning "jest-expo > babel-jest#22.4.3" has unmet peer dependency "babel-
core#^6.0.0 || ^7.0.0-0".
[4/4] Rebuilding all packages...
success Saved lockfile.
success Saved 1 new dependency.
└─ jest-expo#25.1.0-beta.0
warning "jest-expo" is already in "devDependencies". Please remove existing
entry first before adding it to "dependencies".
This is the minimal package.json file of my react native sample project just created to test your cases. Basically you are using CRNA (create-react-native-app) to create your project this is a expo client. See my package.json file below:
{
"name": "AwesomeProject",
"version": "0.1.0",
"private": true,
"devDependencies": {
"react-native-scripts": "1.13.1",
"jest-expo": "26.0.0",
"react-test-renderer": "16.3.0-alpha.1"
},
"main": "./node_modules/react-native-scripts/build/bin/crna-entry.js",
"scripts": {
"start": "react-native-scripts start",
"eject": "react-native-scripts eject",
"android": "react-native-scripts android",
"ios": "react-native-scripts ios",
"test": "jest"
},
"jest": {
"preset": "jest-expo"
},
"dependencies": {
"expo": "^26.0.0",
"react": "16.3.0-alpha.1",
"react-native": "0.54.0"
}
}
You don't need to add babel-cli for basic project read its usage here but if you still need then add it to your dev-dependencies. Also react-dom you still not need because its for reactjs projects not for react-native.
My suggestion is try to read before you start your project and go step by step then you'll not stuck in some irrelevant issue.
What node version are you using? I am asking this because in your question you mentioned the error the code is throwing
path\Property2\AwesomeProject\App.js:1
(function (exports, require, module, __filename, __dirname) { import React,
{ Component } from 'react';
^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:152:10)
at Module._compile (module.js:624:28)
at Object.Module._extensions..js (module.js:671:10)
and it seems like code is having trouble resolving import statements.So it may be that yout babel is not able resolve this new syntax.

Unexpected token import error in while running jest tests

I know this has been asked countless times, but I am not able to fix the problem inspite of following all the SO solutions and suggestions.
I came to know about jest a few days ago and tried to have my hands on it. There is a good tutorial mentioned on DZone about using jest to test react components. However, when I try testing one of the components from the starter directory, I am having this issue,
SyntaxError: Unexpected token import
at ScriptTransformer._transformAndBuildScript (../../../../../../usr/local/lib/node_modules/jest/node_modules/jest-runtime/build/ScriptTransformer.js:289:17)
at emitTwo (events.js:106:13)
As per suggested in this SO post, I have already installed babel-preset-react and added it to my webpack.config.js file.
Here is my webpack.config.js file, my package.json file , the .babelrc file
Please note that I have already gone through the solutions posted in these SO posts -
Link 1
Link 2
Link 3
which might be apparent from the changes in my .babelrc and webpack files
But I'm not able to fix the issue that I'm having. Please let me know if I am missing something here, since I have spent a good 3-4 hrs searching SO and other forums for any answer and I can't seem to find it.
Update 1: Here is my test file - Clock.test.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import Clock from 'Clock';
describe('Clock',()=>{
it("renders without crashing",()=>{
const div = document.createElement('div');
ReactDOM.render(<Clock/>,div);
});
});
I was trying to follow up that tutorial but could not even install it without errors. As I see it, the tutorial is old, webpack 1 is deprecated, and other packages also undergone changes. You could try my steps, but it may not work for you.
In the starter/CountdownTimer folder run npm install. If it throws
this errors: “Cannot read property 'find' of undefined”, then run npm cache verify and npm install.
Then run npm install –save-dev jest#18.0.0 to install jest.
In the app folder create __tests__ folder in there create app.test.jsx
and Clock.test.jsx.
Add “jest” to the package.json test script.
Change your .babelrc.
Here is how the files look like:
// app.test.jsx
describe('App', () => {
it('should be able to run tests', () => {
expect(1 + 2).toEqual(3);
});
});
// Clock.test.jsx
import React from 'react';
import ReactDOM from 'react-dom';
// Note the path.
import Clock from '../components/Clock';
describe('Clock',()=>{
it("renders without crashing",()=>{
const div = document.createElement('div');
ReactDOM.render(<Clock/>,div);
});
});
// package.json
{
"name": "countdown-timer",
"version": "0.0.1",
"description": "",
"main": "server.js",
"scripts": {
"start": "node server.js",
"test": "jest"
},
"author": "Joyce Echessa",
"license": "MIT",
"dependencies": {
"express": "^4.14.0",
"react": "^15.4.0",
"react-dom": "^15.4.0"
},
"devDependencies": {
"babel-core": "^6.18.2",
"babel-loader": "^6.2.8",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0",
"css-loader": "^0.26.0",
"foundation-sites": "^6.2.4",
"jest": "^18.0.0",
"jquery": "^3.1.1",
"node-sass": "^3.13.0",
"sass-loader": "^4.0.2",
"script-loader": "^0.7.0",
"style-loader": "^0.13.1",
"webpack": "^1.13.3"
}
}
// .babelrc
{
"presets": [["es2015"], ["react"]]
}
Run npm test. This worked for me to get tests passing, hope it will help you too.

Categories