Node.js + Typescript + Webpack = Module not found - javascript

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

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

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

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.

Cannot find module 'path'

I'm attempting to learn Typescript and thought I should also make my webpack config in .ts. This is my webpack.config.ts:
import * as webpack from 'webpack';
import * as path from 'path';
const config: webpack.Configuration = {
entry: path.resolve('src/main.ts'),
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.tsx', '.ts', '.js']
},
output: {
filename: 'index.js',
path: path.resolve( 'dist')
}
}
export default config;
As well as my package.json:
"main": "index.js",
"scripts": {
"prebuild": "rimraf dist",
"build": "webpack --config devtools/webpack.config.ts --display-error-details",
"post-build": "webpack-dev-server --config devtools/webpack.config.ts --mode development"
},
"author": "",
"license": "ISC",
"devDependencies": {
"ts-loader": "^4.0.1",
"ts-node": "^5.0.1",
"typescript": "^2.7.2",
"webpack": "^4.1.1",
"webpack-cli": "^2.0.12",
"webpack-dev-server": "^3.1.1"
}
}
The error I get when running npm run build is:
TS2307: Cannot find module 'path'
I have also tried requiring path, but then I get a different error saying it cant find module require.
What seems to be the issue?
This should help
npm i #types/node -D
Typescript needs typings for any module, except if that module is not written in typescript.
Using
"types": ["node"]
in tsconfig.json as mentioned in the comments, solved the issue for me.
I had to do all this
[VS Code][Terminal] upgrade typescript: npm i typescript/#latest -g
[VS Code][Terminal] install node types: npm i #types/node --save-dev
[VS Code][tsconfig.json] add types: "compilerOptions": {types:["node"]}
[VS Code][Explorer] delete package-lock.json and node_modules
[VS Code][Terminal] install: npm install
[VS Code] Restart VS Code
[VS Code][Terminal] test: tsc
Try using require syntax rather than import & change webpack.config.ts to the following code
webpack.config.ts
const webpack = require('webpack');
const path = require('path');
const config: webpack.Configuration = {
entry: path.resolve('src/main.ts'),
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.tsx', '.ts', '.js']
},
output: {
filename: 'index.js',
path: path.resolve( 'dist')
}
}
module.exports = config;
And then run npm run build
First of all no need of .ts extension for webpack config file. Its just internal purpose for building the bundle. Use normal .js file.
Webpack is not ran by browser, its by Node Js which runs webpack module and make bundle as per config.
Now Node Js understand its own module system is which is require
So it would be like below: require in below is Node Js module importing syntax.
const webpack = require('webpack');
const path = require('path');

Webpack looking for index in datatables extension which has none

What I am trying to do is use datatables. I get the error:
ERROR in ./index.js
Module not found: Error: Can't resolve 'datatables.net-dt' in path/src
for all the datatables requires when I try to webpack it. I ran webpack with --display-error-details and found the problem to be that it is looking in the datatable directories for an index file of some sort. e.g.
Field 'browser' doesn't contain a valid alias configuration
path/node_modules/datatables.net-colreorder-dt/index doesn't exist
.js
Field 'browser' doesn't contain a valid alias configuration
path/node_modules/datatables.net-colreorder-dt/index.js doesn't exist
.json
Field 'browser' doesn't contain a valid alias configuration
path/node_modules/datatables.net-colreorder-dt/index.json doesn't exist
I don't understand why it is looking for the index. I have followed all the documentation I can find on webpack and datatables and according to the datatables download section I should only have to add the packages (which I have done) and add the require's part and it should work.
I have looked at the repos for datatables and its extensions and there is no index in any of them. I've googled this in every which way possible and can't find any answer so I'm hoping someone here might have an idea as I have tried many different things which either didn't work or produced even more errors.
This is my index.js
require('./index.html');
var AWS = require('aws-sdk');
require( 'datatables.net-dt' )();
require( 'datatables.net-buttons-dt' )();
require( 'datatables.net-buttons/js/buttons.print.js' )();
require( 'datatables.net-colreorder-dt' )();
require( 'datatables.net-fixedheader-dt' )();
require( 'datatables.net-rowgroup-dt' )();
No code after the requires runs so I haven't included it.
This is my package.json
{
"name": "TestCode",
"version": "1.0.0",
"description": "Test",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
"keywords": [],
"author": " ",
"license": "ISC",
"dependencies": {
"aws-sdk": "^2.116.0",
"datatables.net-buttons-dt": "^1.4.2",
"datatables.net-colreorder-dt": "^1.4.1",
"datatables.net-dt": "^1.10.16",
"datatables.net-fixedheader-dt": "^3.1.3",
"datatables.net-rowgroup-dt": "^1.0.2",
"jquery": "^3.2.1",
"raw-loader": "^0.5.1"
},
"devDependencies": {
"html-webpack-plugin": "^2.30.1",
"json-loader": "^0.5.7",
"webpack": "^3.6.0",
"webpack-dev-server": "^2.9.1"
},
}
and this is my webpack.config.js
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
devtool: 'cheap-module-eval-source-map',
context: path.resolve(__dirname, 'src'),
entry: './index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
devServer: {
contentBase: path.resolve(__dirname, 'src')
},
module: {
loaders: [
{
test: /\.json$/,
loaders: ['json']
},
{
test: /\.html$/,
loader: ['raw-loader']
}
]
},
resolveLoader: {
moduleExtensions: ['-loader']
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
template: './index.html'
})
]
};
First off, your require statements don't need an extra () at the end. require('module'); is fine.
Secondly, you have one statement with a .js extension. It shouldn't be there because you're requiring modules, not files.
Finally, to the solution that fixes your problem: You're missing a resolve field in your webpack.config.js. When you leave the resolve field out, all of the require() statements are looking for modules inside your given context folder, which in your case is the source (src) folder (defaults to root folder when not defined).
To solve this problem, add something like the following to your webpack.config.js:
resolve: {
modules: [
path.resolve('./node_modules')
]
}
Or wherever your node modules may be.
The reason webpack is looking for the index, is because it's default. It couldn't find the module you referenced, so it's looking for an index file instead. The reason you're getting multiple errors on the same import is because it's looking for more than one extension.
The extensions default to extensions: [".js", ".json"]. This is why you see the .js and .json in your error logs. (btw this is also why you can leave extensions out of your require() statements)
If you need more help understanding webpack feel free to ask, or check out https://webpack.js.org/configuration/resolve/ for the documentation on the resolve options for more stuff you can do with resolving your modules.

Import ES6 module from npm package

I created and published my first npm package. This package contains JS in ES6 syntax and is transpiled to ES5 with webpack and babel.
Now I want to use this npm package but it fails with following error:
ERROR in ./node_modules/chokidar/index.js
Module not found: Error: Can't resolve 'fs' in 'C:\dev\git\open-source\test\node_modules\chokidar'
# ./node_modules/chokidar/index.js 3:9-22
# ./node_modules/watchpack/lib/DirectoryWatcher.js
# ./node_modules/watchpack/lib/watcherManager.js
# ./node_modules/watchpack/lib/watchpack.js
# (webpack)/lib/node/NodeWatchFileSystem.js
# (webpack)/lib/node/NodeEnvironmentPlugin.js
# (webpack)/lib/webpack.js
# ./node_modules/technology-radar/webpack.config.js
# ./sample/app.js
For usage I have the following (minimal) set of files
package.json:
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.0",
"babel-preset-es2015": "^6.24.1",
"webpack": "^3.5.6",
"webpack-dev-server": "^2.4.5",
"babel-polyfill": "^6.26.0",
"html-webpack-plugin": "^2.28.0"
},
"dependencies": {
"d3": "3.5.17",
"technology-radar": "^1.0.3"
}
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
module.exports = {
entry: {
sample: './sample/app.js',
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js'
},
module: {
loaders: [
{
loader: 'babel-loader',
include: [
path.resolve(__dirname, "sample")
],
test: /\.js$/
}
]
},
plugins: [
new UglifyJSPlugin(),
new HtmlWebpackPlugin({
template: 'sample/index.html',
filename: 'index.html',
inject: 'body'
})
],
devtool: "#source-map"
};
sample/app.js
import Radar from 'technology-radar';
var radar = new Radar("#techradarContainer");
radar.render();
I don't know if there is in the usage or in the npm package itself.
The sourcecode of the package is available on github at https://github.com/raman-nbg/techradar. The npm package is available at https://www.npmjs.com/package/technology-radar.
The class which should be export (as defined as entry point in the webpack.config.js of the package) is defined src/Radar.js with export default class Radar { ... }. The entry point is defined as
module.exports = {
entry: {
"technology-radar": "./src/Radar.js",
...
}
...
}
You seem to be misunderstanding how publishing and using packages works.
Ignoring Webpack entirely, a standard npm module has main set to the JS file that is the root of your package, and generally packages published to npm are compiled with Babel before being published. Usually before publishing technology-radar, you'd use a package like babel-cli with
babel src -d lib
to compile everything in the src directory into ES5 inside lib. Then
your package.json#main value should be
"main": "./lib/index.js"
or whichever package is the conceptual root of your package. That could be Radar.js in your case, but it's hard to tell.
Because your main is set to webpack.config.js, when you run Webpack inside your actual application, you are trying to bundle Webpack itself for use on in a browser, which does not work because it is a Node application.
If you've done the above and have a technology-radar package that is already processed with Babel, the configuration of your sample application is pretty much what you already have.

Categories