Error: Cannot find module "." mongodb with webpack and typescript - node.js

I have a problem when I can use mongoose with webpack. I already installed it as a dependency but when I want to use the mongoose object and execute it it commands me that it can not find the "." Module. And that seems very strange, I've been looking for a good time, I installed the dependencies again, delete the npm cache, reinstall webpack
I would appreciate your support, thank you very much
webpack.config.js
var path = require("path");
var typescriptLoader = {
test: /\.ts$/,
loader: 'ts-loader'
};
module.exports = {
entry: "./src/main.ts",
target: "node",
output: {
path: path.resolve(__dirname, "dist"),
publicPath: "dist/",
filename: "main.js"
},
node: {
__filename: true,
__dirname: true
},
watch: true,
devServer: {
contentBase: path.join(__dirname, "public_html"),
watchContentBase: true
},
module: {
rules: [ typescriptLoader ]
},
resolve: {
extensions: [ '.js', '.ts' ]
},
externals: {
}
}
package.json
{
"name": "",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"watch": "webpack --config webpack.config.js -p",
"start": "node dist/main.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"karma": "^1.5.0",
"ts-loader": "^2.0.1",
"typescript": "^2.2.1",
"webpack": "^2.2.1"
},
"dependencies": {
"#types/core-js": "^0.9.39",
"#types/helmet": "0.0.34",
"#types/mongoose": "^4.7.10",
"#types/node": "^7.0.11",
"body-parser": "^1.17.1",
"cheerio": "^0.22.0",
"express": "^4.15.2",
"helmet": "^3.5.0",
"mongoose": "^4.9.4",
}
}
index.ts
import * as mongoose from 'mongoose'; // ALL OK
console.log(mongoose); // Error when is used
Error
var n;n="undefined"==typeof window?!function(){var e=new Error('Cannot find module "."');throw e.code="MODULE_NOT_FOUND",e}():r(204),/*!
^
Error: Cannot find module "."

Your mongoose is npm module. TypeScript may not recognized the way you import it. try the nodejs require module loading system.
var mongoose = require('mongoose');
or
const mongoose = require('mongoose');

Related

How to configure webpack 5 to output ts files in dist folder from src folder?

I am using webpack 5 with typescript and a node.js app.
My folder structure is
src/
server.ts
mymodule.ts
public/
index.html
main.ts
utils.ts
but I want to output the compiled files as
dist/
server.js
mymodule.js
public/
index.html
bundle.js
This is my package.json
{
"name": "to-do",
"version": "1.0.0",
"description": "An application for to do list",
"main": "server.js",
"type": "module",
"scripts": {
"start": "node server.js",
"debug": "node --inspect server.js",
"build": "webpack",
"serve": "webpack serve"
},
"license": "MIT",
"dependencies": {
"express": "^4.18.1",
"filenamify": "^5.1.1",
"html-webpack-plugin": "^5.5.0",
"http": "^0.0.1-security",
"ts-loader": "^9.3.1",
"typescript": "^4.7.4",
"webpack": "^5.73.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.9.3"
},
"keywords": [
"todo"
],
"devDependencies": {
"#types/express": "^4.17.13",
"#types/node": "^18.0.6"
}
}
This is my webpack configuration
import path from 'path';
import { fileURLToPath } from 'url';
import HtmlWebpackPlugin from 'html-webpack-plugin';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
export default {
entry: {
bundle : './src/public/main.ts'
},
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
target:'node',
resolve: {
extensions: ['.ts', '.js'],
},
plugins: [
new HtmlWebpackPlugin({
template: 'src/public/index.html',
scriptLoading:"module"
})
],
output: {
filename: '[name].js',
path: path.join(__dirname, 'dist'),
clean: true
},
mode: 'development',
devtool: 'inline-source-map',
devServer: {
hot: true,
static: {
directory: './dist',
},
compress: true,
port: 3002,
headers: {
'Cross-Origin-Embedder-Policy': 'require-corp',
'Cross-Origin-Opener-Policy': 'same-origin'
}
},
stats: {
errorDetails:true
}
};
I get an error about server.js can't be resolved, since I assume it looks at the main from package.json.
ERROR in ./src/public/main.ts 3:0-36
Module not found: Error: Can't resolve './server.js' in 'C:\Users\Desktop\4\src\public'
resolve './server.js' in 'C:\Users\Desktop\4\src\public'
using description file: C:\Users\Desktop\4\package.json (relative path: ./src/public)
using description file: C:\Users\Desktop\4\package.json (relative path: ./src/public/server.js)
no extension
How can I resolve this?

Webpack can't find module css-loader (Error: Cannot find module '.../webpack_tutorial/node_modules/css-loader/dist/cjs.js')

I'm currently learning webpack with the following tutorial on YouTube: https://www.youtube.com/watch?v=MpGLUVbqoYQ&t=1337s&ab_channel=freeCodeCamp.org, i'm on minute 43.
I want that Webpack loads my css, but when I run "node start", and the error "Cannot find module css-loader" occurs, although I have it installed properly.
This is my webpack.config.js:
const path = require('path');
module.exports = {
mode: "development",
entry: "./src/index.js",
output: {
filename: "main.js",
path: path.resolve(__dirname, "dist")
},
module: {
rules: [
{
test: /\.css$/,
use: ["css-loader"]
},
],
}
}
package.json:
{
"name": "webpack_tutorial",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack --config webpack.config.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"webpack": "^5.9.0",
"webpack-cli": "^4.2.0"
},
"devDependencies": {
"css-loader": "^5.0.1",
"style-loader": "^2.0.0"
}
}
index.js:
import { run } from "./app/app";
import "./main.css";
import { AlertService } from "./app/alert.service";
import { ComponentService } from "./app/component.service";
const alertService = new AlertService();
const componentService = new ComponentService();
run(alertService, componentService);
Folder structure:
dist
node_modules
src
app
some other files...
index.js
main.css
package.json
webpack.config.js
Has anyone an idea why webpack is not finding this package?

Babel is not transpiling nodejs modules

I've created a few nodejs modules and trying to bundle them using webpack, after been transpiled using babel. But it seems babel is not transpiling modules.
Following is my project structure:
> config
> connection
> controllers
> models
> node_modules
> routes
.babelrc
.env
.gitignore
chalk.console.js
package-lock.json
package.json
Procfile
index-bundle.js
index.js
webpack.config.js
Following is the package.json
{
"name": "index-service",
"version": "0.1.0",
"main": "index.js",
"scripts": {
"dev-run": "webpack && node index-bundle.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"license": "ISC",
"dependencies": {
"#babel/core": "7.11.6",
"#babel/node": "7.10.5",
"#babel/preset-env": "7.11.5",
"babel-loader": "8.1.0",
"body-parser": "1.19.0",
"core-js": "3.6.5",
"dotenv": "8.2.0",
"express": "4.17.1",
"pg": "8.4.0",
"pg-hstore": "2.3.3",
"regenerator-runtime": "0.13.7",
"sequelize": "6.3.5",
"webpack": "4.44.2",
"webpack-node-externals": "2.5.2",
},
"devDependencies": {
"chalk": "^4.1.0",
"nodemon": "^2.0.4",
"webpack-cli": "^3.3.12"
}
}
Following is the index.js
require('core-js/stable');
require('dotenv').config();
require('regenerator-runtime/runtime');
const chalk = require('./chalk.console');
const bodyParser = require('body-parser');
const express = require('express');
....
app.listen(PORT, () => {
console.log(chalk.info(`Service running on port ${PORT}`));
});
Following is the webpack.config.js
const nodeExternals = require('webpack-node-externals');
module.exports = {
mode: "development",
target: 'node',
externals: [nodeExternals()],
entry: './index.js',
output: {
path: __dirname,
filename: 'index-bundle.js'
},
module: {
rules: [
{
test: /.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
}
]
}
};
Following is the .babelrc file:
{
"presets": [
"#babel/preset-env"
]
}
Following is the chalk.console.js:
const chalk = require('chalk');
const error = chalk.redBright;
const success = chalk.greenBright;
const warning = chalk.hex('#ff3d00');
const info = chalk.yellowBright;
//This is where the error is occuring
export {
error,
success,
warning,
info
};
So, whenever I run npm run dev-run
I get the following error
D:\NodeJS Services\Index\chalk.console.js:8
export {
^^^^^^
SyntaxError: Unexpected token 'export'
The exact same project structure and same .babelrc, webpack.config.js, and package.json dependencies are working in my another project, but not this one. I wonder where did I go wrong

node js webpack Undefined envioronment variable

HHHi,
I'm trying to use the .env file to store the API id and key for the API I'm using and it's not working. My .env file is in the root of my working directory as well as the root of the repository where the .gitignore file is. It looks like this:
API_ID=XXXXXX
API_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXX
I installed dotenv and in my index.js file in my server directory I call it like this:
const dotenv = require('dotenv');
dotenv.config();
then in my apiCall.js function I try to call the variables from the .env file like this:
const AYLIENTextAPI = require('aylien_textapi');
let textapi = new AYLIENTextAPI({
application_id: process.env.API_ID,
application_key: process.env.API_KEY
});
but the ID and Key are showing up as undefined. What am I doing wrong? I would really appreciate any help.
Thanks,
Mike
UPDATE:
this is my webpack.dev.js file:
const path = require('path')
const webpack = require('webpack')
const HtmlWebPackPlugin = require("html-webpack-plugin")
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
module.exports = {
entry: './src/client/index.js',
output : {
libraryTarget: 'var',
library: 'Client'
},
mode: 'development',
devtool: 'source-map',
stats: 'verbose',
module: {
rules: [
{
test: '/\.js$/',
exclude: /node_modules/,
loader: "babel-loader"
},
{
test: /\.scss$/,
use: [ 'style-loader', 'css-loader', 'sass-loader' ]
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/client/views/index.html",
filename: "./index.html",
}),
new CleanWebpackPlugin({
// Simulate the removal of files
dry: true,
// Write Logs to Console
verbose: true,
// Automatically remove all unused webpack assets on rebuild
cleanStaleWebpackAssets: true,
protectWebpackAssets: false
})
]
}
this is my package.json file:
{
"name": "example-project",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node src/server/index.js",
"build-prod": "webpack --config webpack.prod.js",
"build-dev": "webpack --config webpack.dev.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"aylien_textapi": "^0.7.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"webpack": "^4.41.6",
"webpack-cli": "^3.3.11"
},
"devDependencies": {
"#babel/core": "^7.8.4",
"#babel/preset-env": "^7.8.4",
"babel-loader": "^8.0.6",
"clean-webpack-plugin": "^3.0.0",
"css-loader": "^3.4.2",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.9.0",
"node-sass": "^4.13.1",
"optimize-css-assets-webpack-plugin": "^5.0.3",
"sass-loader": "^8.0.2",
"style-loader": "^1.1.3",
"terser-webpack-plugin": "^2.3.5",
"webpack-dev-server": "^3.10.3",
"workbox-webpack-plugin": "^5.0.0"
}
}
figured it out. I can only access the environment variables on the server side.

NODE.JS: Why can't I get live reload with web pack?

IM SO FRUSTRATED RIGHT NOW, ive spent a whole day trying to get webpack to work, but every tutorial or documentation is terrible..it shouldnt be this hard..whats the point of these packages if they actually make you spend more time trying to configure them then saving time.
I just want the live reload to work. I've tried the inline method, iframe, hot module, the middleware with express. None of it works...Im using Node.js on atom, with safari browser.
I want it to work with express.
Can someone point me to a good tutorial...or explain step by step very simply..
Need help. please. no one every replies on these things! Thank you
GITHUB REPO LINK
webpack.config.js
const nodeExternals = require('webpack-node-externals');
module.exports =
{
entry: './app.js',
target: 'node',
externals: [nodeExternals()],
output: {
path: __dirname + '/dist',
filename: 'app.bundle.js',
},
devServer: {
port: 8000,
open: true,
inline: true
},
module: {
loaders: [
{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
}
]
}
}
package.json
{
"name": "clinic8beauty",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"b": "webpack",
"s": "webpack-dev-server",
"test": "echo \"Error: no test specified\" && exit 1"
},
"babel": {
"presets": [
"es2015"
]
},
"author": "Kosta Pontidas",
"license": "ISC",
"dependencies": {
"body-parser": "^1.17.1",
"events": "^1.1.1",
"express": "^4.15.2",
"jquery": "^3.2.1",
"pug": "^2.0.0-beta.12",
"twilio": "^2.11.1",
"validator": "^7.0.0"
},
"devDependencies": {
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-polyfill": "^6.23.0",
"babel-preset-es2015": "^6.24.1",
"node-sass": "^4.5.2",
"pug-html-loader": "^1.1.4",
"sass-loader": "^6.0.3",
"webpack": "^2.4.1",
"webpack-dev-server": "^2.4.4",
"webpack-hot-middleware": "^2.18.0",
"webpack-node-externals": "^1.5.4"
}
}
app.js requires
const express = require('express'),
app = express(),
events = require('events'),
eventEmitter = new events.EventEmitter(),
bodyParser = require('body-parser'),
validator = require('validator'),
client = require('twilio')('AC3cdbdc7ecb720d5521f41243450343e8',
'8f76c52d839dc25aa17ddc72b3b9d781');
You have target node in your config change it to web or remove it as default is web. It should fix your problem.
Can you try the following?
const nodeExternals = require('webpack-node-externals');
const path = require('webpack'); // <== added
module.exports =
{
entry: './app.js',
// target: 'node', <== deleted
externals: [nodeExternals()],
output: {
path: path.resolve(__dirname, 'dist'), //<== added
filename: 'app.bundle.js'
},
devServer: {
port: 8000,
open: true,
inline: true,
contentBase: [path.resolve(__dirname, 'dist')/* add other directories if needed */]
},
module: {
loaders: [
{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
}
]
}
}
And run webpack-dev-server --progress instead of just webpack to start the server
Why not use nodemon globally and webpack to compile

Resources