MongoDB throwing error Module not found: 'module' - mongodb

I have a Mongo db setup on localhost:27017 and and trying to connect to it from my app that uses Webpack via Mongoose. I have Mongoose installed as a package. Here is my code:
import mongoose from 'mongoose';
var db = mongoose.connect('mongodb://localhost:27017/music-app');
mongoose.connection.once('connected', function() {
console.log("Connected to database")
});
I'm pretty sure i've followed the documentation correctly but it's throwing the following compile error:
Error in ./~/mongoose/~/mongodb/~/mongodb-core/~/require_optional/~/resolve-from/index.js
Module not found: 'module' in C:\Users\new\Desktop\Development Projects\music-app\node_modules\mongoose\node_modules\mongodb\node_modules\mongodb-core\node_modules\require_optional\node_modules\resolve-from
There is also another error in the console:
webpackHotDevClient.js:216 Error in ./~/mongoose/~/mongodb/lib/mongo_client.js
Module not found: 'dns' in C:\Users\new\Desktop\Development Projects\music-app\node_modules\mongoose\node_modules\mongodb\lib
# ./~/mongoose/~/mongodb/lib/mongo_client.js 12:10-24
Anyone seen this before and know how to resolve it? Is there additional packages I might need to install in node?

This error is because you're trying to use mongodb from browser, as create-react-app is a front-end app.
You should use a back-end server and use mongodb from there.
You can check out this this full-stack repo having a nodejs server with create-react-app front-end.
https://github.com/fullstackreact/food-lookup-demo

That is because Webpack can’t statically analyze if (typeof window === 'undefined') in mongoose/lib/drivers/index.js
Here is the solution:
webpackConfig.plugins = [
...,
new webpack.DefinePlugin({
'typeof window': "\"object\""
}),
...
]
Also, if you get error messages regarding mongoose, check out below configurations.
npm install node-loader --save-dev
npm install require_optional --save-dev
npm install module --save-dev
webpack.config.js
const webpackConfig = {
name : 'client',
target : 'web',
devtool : config.compiler_devtool,
resolve : {
root : paths.client(),
extensions : ['', '.js', '.jsx', '.json', '.coffee', '.node']
},
node: {
fs: 'empty',
net: 'empty',
tls: 'empty'
},
module : {}
}
// ------------------------------------
// Loaders
// ------------------------------------
// JavaScript / JSON
webpackConfig.module.loaders = [{
test : /\.(js|jsx)$/,
exclude : /node_modules\/(?!(lodash-es)\/).*/,
loader : 'babel',
query : config.compiler_babel
}, {
test : /\.json$/,
loader : 'json'
}, {
test: /\.coffee$/,
loader: 'coffee-loader',
exclude: /node_modules|lib/
}, {
test: /\.node$/,
loader: 'node-loader'
}]

Related

How to pass options to babel plugin transform-modules-commonjs?

I create a Vue 2 project by Vue-Cli 5, then I want to remove "use strick" in the complied code.
As I Know, the #babel/plugin-transform-strick-mode may be enabled via #babel/plugin-transform-modules-commonjs, and the plugin is included in #babel/preset-env under the modules option.
But the Vue-Cli used a preset #vue/babel-preset-app by a plugin #vue/cli-plugin-babel for babel.
So my question is How pass strictMode: false as an option to the transform-modules-commonjs by #vue/babel-preset-app which preset is in the #vue/cli-plugin-babel ?
module.exports = {
presets: [["#vue/cli-plugin-babel/preset", { modules: "auto" }]],
plugins: [
// I tried this way, but it throw many errors like:
/**
ERROR in ./node_modules/axios/dist/node/axios.cjs 11:15-32
Module not found: Error: Can't resolve 'stream' in 'D:\workspace\cqset_offical_website\node_modules\axios\dist\node'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
- install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "stream": false }
*/
["#babel/plugin-transform-modules-commonjs", {}],
[
"component",
{
libraryName: "element-ui",
styleLibraryName: "theme-chalk",
},
],
],
};

Running Nighwatch.js with Babel 7 #babel/register

I have a client repository with React 15.3, Webpack 4, and Babel 7. Webpack works as a charm, but our E2E testing suite using Nightwatch 0.9.20 fails to compile with the new #babel/register package.
Our company is upgrading our babel version from 6 to 7.
Floating around the internet a solution to add the following to the babel.config.js file:
{
"presets": [
[
"#babel/preset-env",
{
"modules": "commonjs",
"targets": {
"node": "current"
}
}
]
],
"plugins": [
"add-module-exports",
]
}
In our instance, this solution doesn't resolve our problem.
I should mention the structure of the project is as follows:
client // where nightwatch is run from the terminal
|-- tests // our E2E tests
|-- nightwatch.conf.js
|-- nighwatch_globals.js
|-- babel.config.js
api // a completely separate repository
|-- tests // we store factory definitions here as well
|-- db
|-- models // also a frequently referenced directory in our E2E tests
Our nightwatch.conf.js structure looks like this:
require('#babel/register')(); // this has been upgraded from 'babel-register'
require('dotenv').config();
...
module.exports = {
// nightwatch configurations
"globals_path": "./nightwatch_globals.js",
// more nightwatch configurations
}
Our nightwatch_globals.js file (where the error is being called looks like this:
import fetch from 'isomorphic-fetch';
module.exports = {
reporter: function(results, cb) {
fetch('http://localhost:4444/selenium-server/driver/?cmd=shutDownSeleniumServer').then(() => {
cb();
if (
(typeof(results.failed) === 'undefined' || results.failed === 0) &&
(typeof(results.error) === 'undefined' || results.error === 0)
) {
process.exit(0);
} else {
process.exit(1);
}
});
},
// give the db some time to finish ops from previous test before
// clearing db and starting the next test
before: function(done) {
require('./../eka-api/test/factories/index.js');
done();
},
beforeEach: function(done) {
setTimeout(function() {
done();
}, 5000);
},
};
And our babel.config.js file is the following:
module.exports = function(api) {
api.cache(true);
const presets = [
"#babel/preset-env",
"#babel/react",
"#babel/preset-flow",
];
const plugins = [
"#babel/plugin-syntax-flow",
"#babel/transform-flow-strip-types",
["#babel/plugin-proposal-decorators", {"legacy": true}],
// react hot loader must come before class properties plugin
"react-hot-loader/babel",
// class properties plugin must come after decorators
// if decorators has a 'legacy' attribute, class properties must be loose
["#babel/plugin-proposal-class-properties", {"loose" : true}],
"#babel/plugin-transform-runtime"
];
return {
presets,
plugins
};
};
From the client directory I run in the terminal node nightwatch.conf.js ; nightwatch
Here is the persisting error
/Users/myUser/Documents/api/test/factories/index.js:1
(function (exports, require, module, __filename, __dirname) { import bluebird from 'bluebird';
^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:74:10)
at Object.runInThisContext (vm.js:116:10)
at Module._compile (module.js:533:28)
at Module._compile (/Users/myUser/Documents/eka-client/node_modules/pirates/lib/index.js:99:24)
at Module._extensions..js (module.js:580:10)
at Object.newLoader [as .js] (/Users/myUser/Documents/eka-client/node_modules/pirates/lib/index.js:104:7)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
at Module.require (module.js:513:17)
My intuition tells me that the reason why the import token is not recognized has to do with how Babel 7 is scoping the compilation of code down to the process.cwd(). As you see the error is coming from the api. Since nightwatch is a package in the client directory, Babel isn't compiling the api directory (which is still on Babel 6). However, I'd like to avoid having to refactor our entire client testing suite to be independent of the api files.
I suspect the solution is to find a way for #babel/register to compile the api from the client side, but I don't know how I'd go about doing something like this.

Webpack with Babel lazy load module using ES6 recommended Import() approach not working

I'm trying to do code splitting and lazy loading with webpack using the import() method
import('./myLazyModule').then(function(module) {
// do something with module.myLazyModule
}
I'm getting
'import' and 'export' may only appear at the top level
Note top level imports are working fine, i'm just getting an issue when I try and using the dynamic variant of import()
var path = require('path');
module.exports = {
entry: {
main: "./src/app/app.module.js",
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "[name]-application.js"
},
module: {
rules: [
{
test: /\.js$/,
use: [{
loader: 'babel-loader',
query: {
presets: ['es2015']
}
}]
}
]
},
resolve : {
modules : [
'node_modules',
'bower_components'
]
},
devtool : "source-map"
}
EDIT:
If I change it so the syntax reads, it works.... but the chunk comments don't work to label the bundle. I'm confused because the documentation says the the following is depreciated.
The use of System.import in webpack did not fit the proposed spec, so
it was deprecated in webpack 2.1.0-beta.28 in favor of import().
System.import('./myLazyModule').then(function(module) {
// do something with module.myLazyModule
}
You need the plugin syntax-dynamic-import to be able to use the import() function with Babel.
Install it with:
npm install --save-dev #babel/plugin-syntax-dynamic-import
And add it to your plugins:
{
presets: ['es2015'],
plugins: ['#babel/plugin-syntax-dynamic-import']
}

Importing css library to ionic project

I am developing an ionic app and i am trying to use the flag-icon-css library (https://github.com/lipis/flag-icon-css). I have installed the library using npm install and added the library to my package.json file
I added the following to my app.scss file:
$flag-icon-css-path: '~flag-icon-css/flags' !default;
#import "~flag-icon-css/sass/flag-icon";
This path is not recognized and i get the following compilation error:
sass: src/app/app.scss, line: 25
File to import not found or unreadable: ~flag-icon-css/sass/flag-icon. Parent style sheet:
/src/app/app.scss
L25: #import "~flag-icon-css/sass/flag-icon";
When changing the path to relative notation, i.e:
$flag-icon-css-path: '../../node_modules/flag-icon-css/flags' !default;
#import '../../node_modules/flag-icon-css/sass/flag-icon';
The code compiles and the css classes are resolved but the app cannot resolve the path to the flags svg files, resulting in a 404 error.
My webpack config:
var path = require('path');
var webpack = require('webpack');
var ionicWebpackFactory = require(process.env.IONIC_WEBPACK_FACTORY);
module.exports = {
entry: process.env.IONIC_APP_ENTRY_POINT,
output: {
path: '{{BUILD}}',
publicPath: 'build/',
filename: process.env.IONIC_OUTPUT_JS_FILE_NAME,
devtoolModuleFilenameTemplate: ionicWebpackFactory.getSourceMapperFunction(),
},
devtool: process.env.IONIC_SOURCE_MAP_TYPE,
resolve: {
extensions: ['.ts', '.js', '.json'],
modules: [path.resolve('node_modules')]
},
module: {
loaders: [
{
test: /\.json$/,
loader: 'json-loader'
},
{
test: /\.ts$/,
loader: process.env.IONIC_WEBPACK_LOADER
}
]
},
plugins: [
ionicWebpackFactory.getIonicEnvironmentPlugin(),
],
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
fs: 'empty',
net: 'empty',
tls: 'empty'
}
};
Any ideas?

How to extend default webpack config in Ionic v2

I'd like to extend the default webpack config of ionic. Specifically, I'd like to add an alias for resolving modules so that I can import modules by their absolute path, rather than a relative one:
Instead of importing modules like this:
import { SomeComponent } from '../../components/some.component.ts';
I want to
import { SomeComponent } from '#app/components/some.component.ts';
where #app is an alias for the root source directory.
In other projects I was able to do this by adding something like this to the webpack config:
module.exports = {
...
resolve: {
extensions: ['.ts', '.js'],
alias: {
'#app': path.resolve('./'),
}
},
...
};
I'm not sure how to do this with Ionic without overriding the default webpack config.
The accepted answer works fine but you will have to update webpack.config.js each time you update app-script. So instead of copying code, require it in webpack.config.js
package.json
"config": {
"ionic_webpack": "./config/webpack.config.js"
}
webpack.config.js
const webpackConfig = require('../node_modules/#ionic/app-scripts/config/webpack.config');
webpackConfig.resolve = {
extensions: ['.ts', '.js'],
alias: {
'#app': path.resolve('./'),
}
}
In most cases you can follow this approach and you wont have to update config each time you update app-script
You may want to copy the existing webpack.config.js file, modify it and configure to use it instead of the initial one.
Here are the steps
On the root folder of your project create config folder and copy the file webpack.config.js there (this file is located in ..\node_modules\#ionic\app-scripts\config
Modify the copied file as required
In the file package.json from your project add:
"config": {
"ionic_bundler": "webpack",
"ionic_webpack": "./config/webpack.config.js"
}
Module path mapping in #Ionic version - 3.14.0
Incase someone is having similar trouble to figure out exact changes to get this working.
In ionic 3 (version 3.14.0), in order to get alias mapping working, you will have to define path mapping both in webpack.config.js & tsconfig.json
package.json
To use custom webpack config, configure your package.json to load your custom webpack.config.js.
"config": {
"ionic_webpack": "./config/webpack.config.js"
}
config/webpack.config.js
Reference the existing webpack
Define the alias path
Merge the alias with default webpack config
...
const path = require('path');
const { dev, prod } = require('#ionic/app-scripts/config/webpack.config');
const webpackMerge = require('webpack-merge');
const customConfig = {
resolve: {
alias: {
'#app': path.resolve('src/app'),
'#pages': path.resolve('src/app/pages'),
'#constants': path.resolve('src/app/constants'),
'#components': path.resolve('src/app/components'),
"#shared": path.resolve('src/app/shared')
}
}
};
module.exports = {
dev: webpackMerge(dev, customConfig),
prod: webpackMerge(prod, customConfig)
};
config/test/webpack.config.js
Reference the existing webpack
Define the alias path
Merge the alias with default webpack config
...
const path = require('path');
const webpackDefault = require('#ionic/app-scripts/config/webpack.config');
const webpackMerge = require('webpack-merge');
const customConfig = {
resolve: {
alias: {
'#app': path.resolve('src/app'),
'#pages': path.resolve('src/app/pages'),
'#constants': path.resolve('src/app/constants'),
'#components': path.resolve('src/app/components'),
"#shared": path.resolve('src/app/shared')
}
}
};
module.exports = webpackMerge(webpackDefault, customConfig);
tsconfig.json
Define baseUrl & paths in tsconfig.json like following:
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"#app/*": ["app/*"],
"#pages/*": ["app/pages/*"],
"#constants/*": ["app/constants/*"],
"#components/*": ["app/components/*"],
"#shared/*": ["app/shared/*"]
}
},
}
Ref: My ionic env info:
cli packages:
#ionic/cli-plugin-proxy : 1.4.13
#ionic/cli-utils : 1.14.0
ionic (Ionic CLI) : 3.14.0
global packages:
cordova (Cordova CLI) : 7.1.0
local packages:
#ionic/app-scripts : 2.1.4
Cordova Platforms : android 6.2.3 ios 4.5.1
Ionic Framework : ionic-angular 3.6.0
Hi Maverick09 answer is awesome but it did not work for me I am using this configuration:
cli packages:
#ionic/cli-utils : 1.15.2
ionic (Ionic CLI) : 3.15.2
local packages:
#ionic/app-scripts : 3.0.1
Ionic Framework : ionic-angular 3.8.0
System:
Node : v6.10.0
npm : 3.10.10
OS : Windows 10
default configuraion has two parts dev and prod so if you change custom config like this seems every thing working
const customConfig = {
dev: {
resolve: {
alias: {
'#app': path.resolve('src/app'),
'#pages': path.resolve('src/pages'),
'#common': path.resolve('src/common'),
'#storyboards': path.resolve('src/storyboards'),
"#locale": path.resolve('src/locale')
}
}
},
prod: {
resolve: {
alias: {
'#app': path.resolve('src/app'),
'#pages': path.resolve('src/pages'),
'#common': path.resolve('src/common'),
'#storyboards': path.resolve('src/storyboards'),
"#locale": path.resolve('src/locale')
}
}
}
};
In recent versions of ionic, alias is not working unless you use this fix (let typescript loader know the alias):
tsconfig.json
"compilerOptions": {
...
"baseUrl": "./src",
"paths": {
"#app/config": ["config/config"]
}
}
...
credit: https://github.com/ionic-team/ionic-app-scripts/pull/683#issuecomment-294078919
My ionic info:
cli packages: (/Users/.../node_modules)
#ionic/cli-plugin-cordova : 1.6.2
#ionic/cli-plugin-ionic-angular : 1.4.1
#ionic/cli-utils : 1.7.0
ionic (Ionic CLI) : 3.7.0
global packages:
Cordova CLI : 7.0.1
local packages:
#ionic/app-scripts : 2.1.3
Cordova Platforms : none
Ionic Framework : ionic-angular 3.6.0
System:
Node : v6.9.5
OS : macOS Sierra
Xcode : Xcode 8.3.3 Build version 8E3004b
ios-deploy : 1.9.1
ios-sim : 5.0.13
npm : 5.3.0