Babel is not transpiling nodejs modules - node.js

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

Related

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.

How to build (Webpack) the Node Js project using PUG Engine?

I am stuck to build the node js project using webpack and I am using pug engine for front end.
My Project Structure:
bin
controller
- csv.controller.js
public
- stylesheets
- javascript
- images
routes
- csv.route.js
- index.route.js
views
- layouts
-- layout.pug
-index.pug
app.js
Package.json File
{
"name": "csv",
"version": "0.0.0",
"private": true,
"scripts": {
"build": "webpack --mode=production",
"build:dev": "webpack --mode=development",
"start":"nodemon ./app.js",
"start:dev": "webpack-dev-server --mode=development"
},
"dependencies": {
"body-parser": "^1.19.0",
"compression": "^1.7.4",
"cookie-parser": "~1.4.4",
"csv-parser": "^2.3.1",
"csv-writer": "^1.5.0",
"debug": "~2.6.9",
"express": "^4.17.1",
"express-fileupload": "^1.1.6-alpha.5",
"fast-csv": "^3.4.0",
"http-errors": "~1.6.3",
"morgan": "^1.9.1",
"multer": "^1.4.2",
"npm-check-updates": "^3.1.23",
"request": "^2.88.0"
},
"devDependencies": {
"#babel/core": "^7.6.2",
"#babel/preset-env": "^7.6.2",
"babel-loader": "^8.0.6",
"clean-webpack-plugin": "^3.0.0",
"css-loader": "^3.2.0",
"extract-text-webpack-plugin": "^3.0.2",
"file-loader": "^4.2.0",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.8.0",
"pug": "^2.0.4",
"pug-loader": "^2.4.0",
"style-loader": "^1.0.0",
"webpack": "^4.40.2",
"webpack-cli": "^3.3.9",
"webpack-dev-server": "^3.8.1",
"webpack-merge": "^4.2.2"
}
}
Actually what I want, after build, A dist folder contain a build.js or whatever its name and all public folder assets in the same directory. I tried with some below codes to build the project.
Webpack.config.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const config = {
entry: {
app: "./app.js"
},
target: "node",
output: {
path: path.resolve(__dirname, "dist"),
filename: "[name].bundle.js"
},
devServer: {
port: 3000
},
plugins: [
new HtmlWebpackPlugin({
template: "./views/index.pug"
})
],
module: {
rules: [
{
test: /\.pug$/,
use: ["pug-loader"]
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ["file-loader"]
},
{
test: [/.js$/],
exclude: /(node_modules)/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"]
}
}
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
}
]
}
};
module.exports = (env, argv) => {
if (argv.mode === "development") {
}
if (argv.mode === "production") {
}
return config;
};
I know this question is old, but just in case somebody is looking for an answer.
You need another Webpack config for app.js, which is express entry point.
Call it webpack.server.js or webpack.server.config.js or whatever convenient. Make sure to include webpack-node-externals:
https://www.npmjs.com/package/webpack-node-externals
It may look something like this:
//webpack.server.js
const path = require('path');
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');
module.exports = {
return ({
entry: {
app: ./src/server/app.js,
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/',
filename: '[name].js',
},
target: 'node',
node: {
__dirname: false,
__filename: false,
},
externals: [nodeExternals()],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
],
},
});
};
Also use webpack-dev-middleware in your app.js.
See the below link:
https://webpack.js.org/guides/development/
In package.json include a script that looks something like this:
"server:dev": "webpack --config webpack.config.js && webpack --mode development --config webpack.server.js && node ./dist/app.js",
In your webpack.config.js make the entry point the js file that imports your front-end assets..
That is your stylesheets and any other js codes..
Not sure what css framework you are using.
But, I am using tailwindcss and I have a js entry point file that imports tailwindcss and my other js codes.
So essentially you may need two webpack config files one for the front-end and one for the express server.
Hope I am making sense.

Express JS with Webpack giving cannot find module error

Hi I am new with frontend technologies so I have a question around webpack and express js. I am building an application using react , webpack , node and express js. The app.js looks like the following
app.js
const express = require('express');
const app = express();
var path = require('path');
app.use(express.static(__dirname + '/'));
app.get('/', (req, res) => { // new
res.sendFile(__dirname + "/index.html");
});
app.listen(3000, () => console.log('listening on port 3000'));
package.json looks like following
"version": "1.0.0",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 0",
"build": "webpack --mode production",
"start": "nohup webpack-dev-server --mode development --open &",
"prepublishOnly": "cp -r configuration/* build/"
},
"repository": {
"type": "git",
"url": "ssh://git.amazon.com/pkg/SPSWebApplication"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.3.4",
"#babel/preset-env": "^7.3.4",
"#babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.5",
"express": "^4.16.4",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"react-dom": "^16.8.4",
"webpack": "^4.29.6",
"webpack-cli": "^3.3.0",
"webpack-dev-middleware": "^3.6.1",
"webpack-dev-server": "^3.2.1"
},
"dependencies": {
"#stencil-react/core": "*",
"#stencil-react/theme-default": "*",
"webpack": "^4.29.6",
"webpack-cli": "^3.3.0",
"react": "^16.8.4",
"webpack-dev-server": "^3.2.1",
"html-webpack-plugin": "^3.2.0"
},
"description": ""
}
webpack.config.js
const HtmlWebPackPlugin = require("html-webpack-plugin");
module.exports = {
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
use: [
{
loader: "html-loader",
options: { minimize: true }
}
]
}
]
},
resolve: { // this allows to import 'Foo.jsx'
extensions: ['.jsx', '.js', '.json']
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
})
]
};
when i build the code in the build folder it creates dist/app.js,main.js,index.html whenever i try to run app.js it says
Error: Cannot find module 'express'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:649:15)
at Function.Module._load (internal/modules/cjs/loader.js:575:25)
at Module.require (internal/modules/cjs/loader.js:705:19)
at require (internal/modules/cjs/helpers.js:14:16)
I want to run my application in production environment through dist/app.js but when I do "node app.js" it gives me this dependency issue I am assuming webpack should pull the express dependency in dist/* folder in a minified form which i am assuming it is not doing. Can you please if I am missing anything and my understanding is correct or not?

npx webpack Unexpected token :

I am trying to use Webpack for the first time with Node and Babel (this is my first time using Babel as well) on Windows 10. I think I have everything configured properly, but it's giving me a cryptic error:
The same thing happens if I do npx webpack --exec bable-node.
In everything I've read about this, it gives a line number. I'm not sure what's the issue.
I have all of the files I thought were related to Node in a folder called "node", and all the other files in a folder called "src". I don't know if this is causing the issue. Here is the folder structure:
/node
/config
/node_modules
.babelrc
master-updated.sh
package-lock.json
package.json
server2.js
webpack.config.js
/src
/model (this is has a bunch of js files, but I removed the references to them for now)
/public
/html
/srcipts
/stylesheets
/css
/scss
/vue
.gitignore
master-updated.sh is a shell script for responding to a GitHub webhook.
Here is the beginning of server2.js:
'use strict';
process.env.NODE_CONFIG_DIR = './node/config';
const config = require('config'),
babel = require('babel-core'),
ejs = require('ejs'),
util = require('util'),
express = require('express'),
bodyParser = require('body-parser'),
cors = require('cors'),
moment = require('moment'),
plaid = require('plaid'),
mariadb = require('mariadb'),
fs = require('fs'),
http = require('http'),
https = require('https'),
session = require('express-session'),
exec = require('child_process').exec;
const GOOGLE_AUTH_CLIENT_ID = '<REDACTED>';
const { OAuth2Client } = require('google-auth-library');
const googleAuthClient = new OAuth2Client(GOOGLE_AUTH_CLIENT_ID);
const APP_PORT = config.APP_PORT;
Here is my webpack.config.js file:
module.exports = {
target: 'node',
entry: {
app: ['./server2.js']
},
output: {
filename: 'server.js',
path: path.resolve(__dirname, 'test')
},
module: {
loaders: [
test: '/\.js$/',
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ["#babel/preset-env"]
}
]
}
}
Here is .babelrc:
{"presets": ["#babel/preset-env"]}
And here is package.json:
{
"name": "sage-savings",
"version": "0.0.1",
"description": "An app for easy budgeting.",
"main": "server2.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --config node/webpack.config.js",
"start": "node node/server2.js"
},
"author": "Dakota Dalton",
"repository": "https://github.com/1silvertiger/Sage",
"license": "ISC",
"dependencies": {
"#types/express": "^4.16.1",
"aws-sdk": "^2.397.0",
"body-parser": "^1.18.3",
"config": "^3.0.1",
"cors": "^2.8.5",
"ejs": "^2.5.9",
"express": "4.16.x",
"express-session": "^1.15.6",
"google-auth-library": "^3.0.1",
"mariadb": "^2.0.3",
"moment": "^2.22.2",
"mysql": "^2.16.0",
"plaid": "2.x.x"
},
"devDependencies": {
"#babel/core": "^7.3.4",
"#babel/preset-env": "^7.3.4",
"ajv": "^6.10.0",
"babel-core": "^6.26.3",
"babel-loader": "^8.0.5",
"babel-preset-env": "^1.7.0",
"typescript": "^3.3.3333",
"webpack": "^4.29.6",
"webpack-cli": "^3.2.3"
}
}
These syntax problems are easily identified if you use an IDE which has syntax highlighting, for example VS Code. All I did was copy your config into a file and load it into VS Code.
You are incorrectly closing the regular expression used for exclude:
exclude: /node_modules\,
You must use a forward slash instead of a back slash:
exclude: /node_modules/
You also need to wrap your loader in an object literal:
loaders: [
{ // <= wrap in object literal
test: '/\.js$/',
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ["#babel/preset-env"]
}
}
]

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

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');

Resources