Error: knex: Required configuration option 'client' is missing - javascript

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.

Related

migration-mongo not treated as common js

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

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

Jest or Mocha with Vue: SyntaxError: Cannot use import statement outside a module

Edit: This post got out of hand with edits, please follow this link to a new Stackoverflow post which is clearer:
SyntaxError: Cannot use import statement outside a module when following vue-test-utils official tutorial
There are thousands of posts and threads about this issue and I still can't fix my problem.
I followed the "Getting started" portions of Jest AND Mocha and get the same error both times:
SyntaxError: Cannot use import statement outside a module but their provided link doesn't help at all.
Theres a new edit at the bottom with steps for a clean new project with jest for you to follow along which results in an error.
"vue-jest": "^3.0.7",
"vue": "^2.6.12",
"#vue/test-utils": "^1.2.2"
package.json
"mocha": "mocha 'tests/Frontend/**/*.test.js'"
example.test.js:
import { mount } from "#vue/test-utils"
import Dashboard from "../../resources/js/views/Dashboard";
import * as assert from "assert";
describe('test example', () => {
it('should work', () => {
assert.equal([1, 2, 3].indexOf(4), -1); // doesn't matter what I do here
})
})
What I've tried:
Using the --require #babel/register flag with mocha
Setting "transformIgnorePatterns": [] and thus allowing all node_modules to be considered
Adding a .babelrc file with the following content: This resulted in following error on building the app though:
Error: Multiple configuration files found. Please remove one:
- package.json
- C:\Users\f.marchi\workspace\projects\sanctum-test\.babelrc
{
"env": {
"test": {
"plugins": ["transform-es2015-modules-commonjs"]
}
}
}
Can someone confirm, that those docs are missing some very important steps? I really don't know what I'm doing wrong, I'm just following the tutorials.
Edit: jest.config.js:
module.exports = {
clearMocks: true,
collectCoverage: true,
coverageDirectory: "coverage",
moduleFileExtensions: [
"js",
"json",
"vue"
],
transform: {
".*\\.(vue)$": "vue-jest"
},
transformIgnorePatterns: []
};
Edit:
I just tried again, you can follow along if you want:
vue create jest-test
npm install --save-dev jest #vue/test-utils vue-jest
Added jest config to package.json:
{
"jest": {
"moduleFileExtensions": [
"js",
"json",
"vue"
],
"transform": {
".*\\.(vue)$": "vue-jest"
}
}
}
npm install --save-dev babel-jest #babel/core #babel/preset-env babel-core#^7.0.0-bridge.0
Adjusted jest config to:
{
"jest": {
"transform": {
// process `*.js` files with `babel-jest`
".*\\.(js)$": "babel-jest" //<-- changed this
}
}
}
Adjusted babel config to:
module.exports = {
presets: [
'#vue/cli-plugin-babel/preset',
'#babel/preset-env' //<-- added this
]
};
You should use vue-cli API.
In your package.json add to scripts this:
"test:unit": "vue-cli-service test:unit"
You have vue-cli and test-utils installed so it should now work.

how can I use top level "await" in typescript next.js

When I use "await" on top-level like this:
const LuckyDrawInstance=await new web3.eth.Contract(abi)
I got a warning on the terminal: "set experiments.topLevelAwait true". When I tried to add this to "tsconfig.json", it still does not work. it says "experiments" property does not exist.
I could wrap it inside an async function but I want to set it without a wrapped function.
It is nothing to do with the tsconfig.json. You have to set it inside next.config.js. New version of next.js uses webpack5 and webpack5 supports top level await.
module.exports = {
webpack: (config) => {
// this will override the experiments
config.experiments = { ...config.experiments, topLevelAwait: true };
// this will just update topLevelAwait property of config.experiments
// config.experiments.topLevelAwait = true
return config;
},
};
NOTE
You have to use it outside the functional component:
export default function Navbar() {
// this will throw error
// Syntax error: Unexpected reserved word 'await'.
const provider=await customFunction()
return (
<section>
</section>
);
}
Warning
Since it is experimental, it might be broken in some versions
The latest solution as of writing this post that worked for me is using Babel instead of SWC since Next.js does not allow custom SWC configuration, therefore, you cannot allow topLevelAwait through .swcrc file.
Add Babel plugin called #babel/plugin-syntax-top-level-await into your package.json.
eg.
{
"devDependencies": {
"#babel/plugin-syntax-top-level-await": "^7.14.5"
}
}
Create .babelrc file in the root directory of your project where package.json lives.
Inside .babelrc make sure to include next/babel preset and the topLevelAwait plugin.
eg.
{
"presets": ["next/babel"],
"plugins": [
"#babel/plugin-syntax-top-level-await"
]
}
This is the easiest solution until Next.js team allows us to include SWC configuration. Note that by doing this you will not have SWC performance benefit since it will be disabled in favor of Babel.
I have been struggling with this for 2-3 days. Here is a solution that works. Please follow the following steps.
1. Copy paste the following in your package.json
{
"name": "projectname",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "mocha",
"dev": "next dev"
},
"author": "",
"license": "ISC",
"dependencies": {
"#truffle/hdwallet-provider": "^2.0.1",
"fs-extra": "^10.0.0",
"ganache-cli": "^6.12.2",
"mocha": "^9.1.4",
"next": "^12.0.8",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"solc": "^0.8.9",
"web3": "^1.7.0",
"#babel/plugin-syntax-top-level-await": "^7.14.5"
},
"devDependencies": {
"#babel/plugin-syntax-top-level-await": "^7.14.5"
}
}
2. Delete your node_modules folder
3. Goto your project's root directory and reinstall all the packages using npm install command
4. Create a new file in your project's root directory and call it "next.config.js"
5. Copy paste following code in next.config.js file and save.
module.exports = {
// target: 'experimental-serverless-trace',
webpack: (config) => {
config.experiments = config.experiments || {};
config.experiments.topLevelAwait = true;
return config;
},
};

Node.js + Typescript + Webpack = Module not found

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'
]

Categories