I have a nodejs server part in my project in which I have defined migre-mongo.
My type in package.json is module. Running the migration leads to
> migrate-mongo up && node node.js
ERROR: 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 '/home/igharib/IdeaProjects/sdx-licence-manager/server/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 '/home/igharib/IdeaProjects/sdx-licence-manager/server/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at file:///home/igharib/IdeaProjects/sdx-licence-manager/server/migrate-mongo-config.js:34:1
at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:385:24)
at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)
at async Object.read (/usr/local/lib/node_modules/migrate-mongo/lib/env/config.js:69:30)
And when I change the config extention into csj as recommanded I get file not found!
ERROR: Cannot find module '/home/igharib/IdeaProjects/sdx-licence-
manager/server/migrate-mongo-config.js'
Require stack:
- /usr/local/lib/node_modules/migrate-mongo/lib/utils/module-loader.js
- /usr/local/lib/node_modules/migrate-mongo/lib/env/config.js
- /usr/local/lib/node_modules/migrate-mongo/lib/env/migrationsDir.js
- /usr/local/lib/node_modules/migrate-mongo/lib/actions/init.js
- /usr/local/lib/node_modules/migrate-mongo/lib/migrate-mongo.js
- /usr/local/lib/node_modules/migrate-mongo/bin/migrate-mongo.js Error: Cannot find module '/home/igharib/IdeaProjects/sdx-licence-manager/server/migrate-mongo-config.js'
My package json:
{
"name": "server",
"version": "0.8.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "react-scripts test",
"start": "NODE_ENV=production node app.js",
"start:migrate": "migrate-mongo up && node node.js",
"start:win": "SET NODE_ENV=production && node app.js",
"start:srv": "node index.js",
"dev": "nodemon --watch src/server/ app.js",
"backend:test": "jest server --runInBand --forceExit --detectOpenHandles --verbose",
"backend:test-coverage": "jest server --collect-coverage --runInBand --forceExit --detectOpenHandles --verbose",
"lint:server": "eslint server app.js"
},
"author": "Iman",
"license": "",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"express-session": "^1.17.2",
"fetch": "^1.1.0",
"jwt-simple": "^0.5.6",
"mongoose": "^5.13.2",
"nodemon": "^2.0.10"
}
}
created migrate config:
// In this file you can configure migrate-mongo
const config = {
mongodb: {
url: "mongodb://localhost:27017",
databaseName: "ldb",
options: {
useNewUrlParser: true, // removes a deprecation warning when connecting
useUnifiedTopology: true, // removes a deprecating warning when connecting
// connectTimeoutMS: 3600000, // increase connection timeout to 1 hour
// socketTimeoutMS: 3600000, // increase socket timeout to 1 hour
}
},
// The migrations dir, can be an relative or absolute path. Only edit this when really necessary.
migrationsDir: "migrations",
// The mongodb collection where the applied changes are stored. Only edit this when really necessary.
changelogCollectionName: "changelog",
// The file extension to create migrations and search for in migration dir
migrationFileExtension: ".js",
// Enable the algorithm to create a checksum of the file contents and use that in the comparison to determine
// if the file should be run. Requires that scripts are coded to be run multiple times.
useFileHash: false,
// Don't change this, unless you know what you're doing
moduleSystem: 'commonjs',
};
module.exports = {config};
How can I solve the problem without changing the type=module?
Node version 16.15.0
Since you are using '"type": "module"', in your migrations config file you should change the last line:
module.exports = {config};
to:
export default config;
That should solve the issue
Related
I am trying to create and run a simple TypeScript NodeJS project. Followings are my codes:
server.ts:
import express from 'express';
const app = express();
const PORT = 3000;
app.listen(PORT , ()=>{
console.log('Server is listening on port $PORT');
});
tsconfig.json:
{
"compilerOptions": {
"target": "esnext", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
"module": "commonjs", /* Specify what module code is generated. */
"rootDir": "./src", /* Specify the root folder within your source files. */
"moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
"outDir": "./build", /* Specify an output folder for all emitted files. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
"strict": true, /* Enable all strict type-checking options. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}
package.json:
{
"name": "back",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon build/server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"#types/express": "^4.17.13",
"express": "^4.18.1",
"mongoose": "^6.5.0",
"nodemon": "^2.0.19"
}
}
When I try npm start I get the following error message:
> back#1.0.0 start
> nodemon build/server.js
[nodemon] 2.0.19
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node build/server.js index.js`
node:internal/modules/cjs/loader:936
throw err;
^
Error: Cannot find module 'C:\Users\A\\Test\back\index.js'
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}
[nodemon] app crashed - waiting for file changes before starting...
You've set your entry file to be index.js in package.json, so nodemon is trying to run both server.js and index.js, which does not exist. The simplest way you can solve this − provided that you've transpiled your TS files with tsc, for example − is to change the entry point main in package.json to build/server.js.
So what you have to do:
Install typescript to be able to transpile you code:
npm install typescript
Before running npm start, you have to make sure your code is transpiled, that is, "compiled" to vanilla JavaScript, so add this script to your package.json:
{
"scripts": {
// ...
"build": "tsc"
}
}
Update main in package.json to be build/server.js.
Run npm run build then finally npm start.
Done! Your server will start.
My tips before the answer update:
Also, creating a configuration file for nodemon (nodemon.json) will make things much simpler for you, take a look at the docs.
Lastly, if you're new at this, I recommend taking a look at some ready-made tsconfig bases from this repo, in special this one for Node 16.
I modified my tsconfig.json file as following and it worked:
{
"name": "back",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon src/server.ts"
},
"author": "",
"license": "ISC",
"dependencies": {
"#types/express": "^4.17.13",
"express": "^4.18.1",
"mongoose": "^6.5.0"
},
"devDependencies": {
"nodemon": "^2.0.19",
"ts-node-dev": "^2.0.0",
"typescript": "^4.7.4"
}
}
The created changes are in these lines:
"main": "index.js" To "main": "server.js"
"start": "nodemon build/server.js" To "start": "nodemon src/server.ts"
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
I'm new to Node.js, please help me.
What is wrong?
Using typescript, SQLite3 and Knex, with migration.
I get the error when running "yarn knex: migrate" or "knex migrate: latest":
$ knex migrate:latest
Requiring external module ts-node/register
Error: knex: Required configuration option 'client' is missing
These are my files:
package.json:
{
"name": "backend",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "ts-node-dev --transpile-only --ignore-watch node-modules --respawn
src/server.ts",
"knex:migrate": "knex --knexfile knexfile.ts migrate:latest",
"knex:migrate:rollback": "knex --knexfile knexfile.ts migrate:rollback"
},
"devDependencies": {
"#types/express": "^4.17.11",
"ts-node": "^9.1.1",
"ts-node-dev": "^1.1.6",
"typescript": "^4.2.4"
},
"dependencies": {
"espress": "^0.0.0",
"express": "^4.17.1",
"knex": "^0.95.4",
"sqlite3": "^5.0.2"
}
}
knexfile.ts:
import path from'path';
module.exports = {
cliente: 'sqlite3',
connection: {
filename: path.resolve(__dirname, 'src', 'database', 'resp.sqlite')
},
migrations: {
directory: path.resolve(__dirname, 'src', 'database', 'migrations'),
},
useNullAsDefault: true,
};
Migration 00_create_organizacoes.ts:
import knex from 'knex';
export async function up(knex: knex) {
return knex.schema.createTable('organizacoes', table => {
table.increments('id').primary();
table.string('razaosocial_org').notNullable();
table.integer('atividade_org').notNullable();
table.timestamp('criacao_org').defaultTo(knex.fn.now());
table.timestamp('atualizacao_org').defaultTo(knex.fn.now());
});
}
export async function down(knex: knex) {
return knex.schema.droptable('organizacoes');
};
My file structure:
enter image description here
Unsuccessful in other treatments.
Looks like you have a typo in your knexfile.ts
The name of the missing property is client and not cliente
The Requiring external module ts-node/register message you get is not the issue, the issue is that in the knexfile.ts the client property is not read. From the example above change the cliente property to client and it is fixed.
What if you have no spelling error, client exist in your configuration, and you are getting this message? Are you using a env file? If yes, In your knexfile.ts print the value from your env file. If it returns undefined, it means that no value was read for the env file. Check if you have the dotenv package installed and configured properly. Also check that your env file has a key called client and the value is available and in the knexfile.ts ensure you are calling the right key from your env.
Finally if the problem is not solved and every other thing is in-place, require dotenv in your package.json file before running a command as shown below.
"migrate:latest": "ts-node -r dotenv/config ./node_modules/knex/bin/cli.js migrate:latest
The ts-node -r dotenv/config ensures that the details in the env file are added to the environment.
The ./node_modules/knex/bin/cli.js starts the knex cli so that the remaining part which is a knex command can be executed.
I am working on a tool and I have installed some modules locally through NPM, and I get errors when I try to require these modules through NodeJS. I am working in Windows 10, I have already tried setting up NODE_PATH etc.
Below is the structure of my files:
->project
---->node_modules
---->src
-------->css
-------->js
----------->index.js
---->package.json
---->index.html
I populate the index.html by using index.js etc.
Below is the code of my package.json:
{
"name": "bip39",
"version": "1.0.0",
"description": "A tool for converting BIP39 mnemonic phrases to addresses and private keys.",
"directories": {
"test": "tests"
},
"dependencies": {
"bip39": "^2.6.0",
"bigi": "^1.4.2",
"create-hmac": "^1.1.7",
"nem-sdk": "^1.6.7"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/PavlosTze/bip39.git"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/PavlosTze/bip39/issues"
},
"homepage": "https://github.com/PavlosTze/bip39#readme"
}
Below is my require() code:
var createHmac = require("create-hmac");
var BigInteger = require("bigi");
const bip39 = require("bip39");
const nem = require("nem-sdk").default;
I have done the following steps on NPM:
1) npm init
2) npm install bip39
3) npm install nem-sdk
4) npm install bigi
5) npm install create-hmac
All these files are inside the node_modules, but still, whenever I run the code in the browser I get an 'Error: Cannot find module "bip39"', etc. for all modules.
EDIT: On another directory that I have cloned the same tool, before I merged it with another one, I get no error and everything works correctly, including the require(). etc. Do you need any of those files as well?
Can someone help me please?
try this :
rm -rf node_modules
npm install
I'm new with Webpack, Node.js and Typescript and I'm having trouble configuring my dev enviroment.
When running webpack to compile my src/server.ts to generate the /server/bundle.js I'm getting this error:
ERROR in ./src/server.ts
Module not found: Error: Can't resolve 'hapi' in '/Volumes/Dados/giovane/dev/studio-hikari/nodang/nodang-api/src'
# ./src/server.ts 3:11-26
The architecture of the project is:
The src/server.ts:
import * as Hapi from 'hapi';
const server = new Hapi.Server();
The webpack.config.js:
const path = require('path');
module.exports = {
entry: './src/server.ts',
output: {
filename: './server/bundle.js'
},
resolve: {
extensions: ['.ts'],
modules: [
path.resolve('src'),
path.resolve('node_modules')
]
},
module: {
loaders: [
{
test: /.ts$/,
loader: 'awesome-typescript-loader'
}
]
}
};
The package.json:
{
"name": "nodang-api",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"compile": "webpack --progress --watch",
"serve": "node-dev server/bundle.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"#types/hapi": "^16.0.0",
"lodash": "^4.17.4"
},
"devDependencies": {
"awesome-typescript-loader": "^3.0.8",
"tsd": "^0.6.5",
"typescript": "^2.2.1",
"webpack": "^2.2.1"
}
}
OBS: It's webpack 2
UPDATE
After installing hapi and adding .js to webpack's resolve extentions and node as webpack's target I'm getting this erros with hapi modules:
ERROR in ./~/hapi/lib/server.js
Module not found: Error: Can't resolve 'catbox' in '/Volumes/Dados/giovane/dev/studio-hikari/nodang/nodang-api/node_modules/hapi/lib'
# ./~/hapi/lib/server.js 5:15-32
# ./~/hapi/lib/index.js
# ./src/server.ts
ERROR in ./~/hapi/lib/server.js
Module not found: Error: Can't resolve 'catbox-memory' in '/Volumes/Dados/giovane/dev/studio-hikari/nodang/nodang-api/node_modules/hapi/lib'
# ./~/hapi/lib/server.js 6:21-45
# ./~/hapi/lib/index.js
# ./src/server.ts
You did not install hapi. #types/hapi are just the type definitions that TypeScript uses for the library, but not the actual library itself. So you need to add hapi as well:
npm install --save hapi
Once you've installed it, the module can be found, although you'll get a new error that ./server could not be resolved in hapi/lib/index.js and that's because you configure resolve.extensions to only include .ts, but the library makes use of Node automatically resolving .js when leaving off the extension. So you also need to include .js in the extensions:
extensions: ['.ts', '.js'],
After also resolving this issue, you'll be faced with another one, namely that Node built-in modules like fs can't be resolved. By default webpack builds for the web, so the Node built-in modules are not available. But you can change that by setting the target option in your webpack config to node:
target: 'node'
Edit
You're having trouble with other node_modules because you only use the top level node_modules, instead you want to always fall back to the regular module resolution of node_modules, so the resolve.modules should look like this:
modules: [
path.resolve('src'),
'node_modules'
]