I'm trying to run the yarn start_dev command inside my main directory C:\Users \THIAGOSAAD\Documents\DEVELOPMENT\NEORIS\ALIANSCE\aliansce-app-analyticals-panel
However when doing this it starts to give error in my "process.env.DATABASE_URL" as if it did not recognize my "dotenv" that is in the "environment" folder!
consign v0.1.6 Initialized in C:\Users\THIAGOSAAD\Documents\ DEVELOPMENT\NEORIS\ALIANSCE\aliansce-app-analyticals-panel
C:\Users\THIAGOSAAD\Documents\DEVELOPMENT\NEORIS\ALIANSCE\aliansce-app-analyticals-panel\node_modules\mongoose\lib\connection.js: 428
throw new MongooseError ('The `uri` parameter to` openUri () `must be a +
^
MongooseError: The `uri` parameter to` openUri () `must be a string, got" undefined ". Make sure the first parameter to `mongoose.connect ()` or `mongoose.createConnection ()` is the string.
at new MongooseError (C: \Users\THIAGOSAAD\Documents\DEVELOPMENT\ NEORIS\ALIANSCE\aliansce-app-analyticals-panel\node_modules\mongoose\lib\ error\mongooseError.js: 13:11)
at NativeConnection.Connection.openUri (C:\Users\THIAGOSAAD\Documents\ DEVELOPMENT\NEORIS\ALIANSCE\aliansce-app-analyticals-panel\node_modules\ mongoose\lib\connection.js: 428:11)
at Mongoose.connect (C:\Users\THIAGOSAAD\Documents\DEVELOPMENT\ NEORIS \ ALIANSCE\aliansce-app-analyticals-panel\node_modules\mongoose\lib\ index.js: 270: 15)
If I enter the url directly on my server.js it starts to give errors in my consign:
consign v0.1.6 Initialized in C:\Users\THIAGOSAAD\Documents\DEVELOPMENT \NEORIS\ALIANSCE\aliansce-app-analyticals-panel
! Entity not found C:\Users\THIAGOSAAD\Documents\DEVELOPMENT\NEORIS\ALIANSCE\aliansce-app-analyticals-panel\routes
! Entity not found C:\Users\THIAGOSAAD\Documents\DEVELOPMENT\NEORIS\ ALIANSCE \ aliansce-app-analyticals-panel\controllers
SERVER ROLLING IN PORT 3000: ')
But if I run the nodemon from the directory where the start.js is, it works: C: \Users\THIAGOSAAD\Documents\DEVELOPMENT\NEORIS\ALIANSCE\aliansce-app-analyticals-panel\app\backend\src\start.js
I would like to know why this happens and how to solve it, because I'm trying to upload the server to Heroku and it's not running, probably because of the same problem running yarn start_dev!
MY DIRECTORIES
SERVER.JS
const express = require('express');
const dotenv = require('dotenv');
const morgan = require('morgan');
const consign = require('consign');
const mongoose = require('mongoose');
const nunjucks = require('nunjucks');
class Application {
constructor(){
this.express = express();
this.dotenv = dotenv.config({ path: './environment/.env' });
this.morgan = morgan('dev');
this.consign = consign();
this.mongoose = mongoose;
this.nunjucks = nunjucks;
// INICIALIZA AS FUNÇÕES AUTOMATICAMENTE
this.initDatabase();
this.initMiddlewares();
this.initConsign();
this.initViews();
}
initDatabase(){
this.mongoose.connect(process.env.DATABASE_URL, {
useCreateIndex: true,
useNewUrlParser: true
});
}
initMiddlewares(){
this.express.set('view engine', 'njk');
this.express.use(express.static('../../app/frontend'));
this.express.use(express.json());
this.express.use(express.urlencoded({ extended: true }));
this.express.use(this.morgan);
}
initConsign(){
this.consign.include('./routes').then('./controllers').into(this.express);
}
initViews(){
this.nunjucks.configure('./views/pages', {
watch: true, // SOMENTE PARA DESENVOLVIMENTO
express: this.express,
autoescape: true
});
}
}
module.exports = new Application().express;
PACKAGE.JSON
{
"author": "THIAGO DE BONIS CARVALHO SAAD SAUD",
"scripts": {
"start_dev": "nodemon app/backend/src/start.js"
},
"dependencies": {
"axios": "^0.18.0",
"bootstrap": "^4.2.1",
"bootstrap-select": "^1.13.5",
"chartjs": "^0.3.24",
"consign": "^0.1.6",
"dotenv": "^6.2.0",
"express": "^4.16.4",
"express-validator": "^5.3.1",
"jquery": "^3.3.1",
"jsonwebtoken": "^8.4.0",
"mongoose": "^5.4.1",
"nunjucks": "^3.1.6"
},
"devDependencies": {
"morgan": "^1.9.1",
"nodemon": "^1.18.9"
}
}
When setting the dotenv folder path set the absolute path.
this.dotenv = dotenv.config({ path: require('path').join(__dirname, './environment') });
Related
I've been trying to deploy my Express application on Heroku and the build gets created successfully but when I try to open it, I'm greeted with an error message that basically states that the page could not be served.
So, I run heroku logs --tail and then I get the following error messages :
One half of the error messages
Remaining half of the error messages
File Tree
Procfile
web: node server.js
Package.json
{
"name": "conduit-api",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt": "^5.0.1",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"nodemon": "^2.0.12",
"pg": "^8.7.1",
"pg-hstore": "^2.3.4",
"redux-persist": "^6.0.0",
"sequelize": "^6.6.5"
},
"devDependencies": {
"cross-env": "^7.0.3"
}
}
server.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const { sequelize } = require('./src/entities/User/User');
const db = require('./src/config/Database');
const feedRoute = require('./src/routes/Feed/Feed');
const usersRoute = require('./src/routes/Users/Users');
const userRoute = require('./src/routes/User/User');
const articlesRoute = require('./src/routes/Articles/Articles');
const profilesRoute = require('./src/routes/Profiles/Profiles');
const commentsRoute = require('./src/routes/Comments/Comments');
const app = express();
app.use(cors());
app.use(bodyParser.json());
// Routes
app.use('/api/feed', feedRoute);
app.use('/api/users', usersRoute);
app.use('/api/user', userRoute);
app.use('/api/articles', articlesRoute);
app.use('/api/profiles', profilesRoute);
app.use('/api/articles', commentsRoute);
// REQUESTS
app.get('/', async (req,res) => {
res.json('Yooooooooooo')
try {
await db.authenticate();
console.log('Connection has been established');
} catch(err) {
console.log('Error');
}
})
// To START sequelize and also wipes the DB clean
// async function main() {
// await sequelize.sync({force: true})
// }
// main()
// TO START sequelize
const PORT = process.env.PORT || 3000;
app.listen(PORT , () => {
console.log(`App is listening to ${PORT}`);
})
I've tried modifying my procfile and removing and re-installing the modules but the problem still persists.
I've been stuck on this for days now and any sort of help would be highly appreciated.
Looks like you problem is your pointing the main in package.json to a file that doesn't exist.
Package.json
"main": "index.js"
Your app seems to deploy from you server.js file.
The main field is a module ID that is the primary entry point to your program.
as per documentation: https://docs.npmjs.com/cli/v7/configuring-npm/package-json#main
I am adding a sequelize to my node project, it adds the following index.js file as a part of the setup, but when I run the project the __dirname resolves to my C: directory instead of the project root folder
C:\workspace\myapp. How do I configure it so that it resolves to my project root directory?
index.js file
'use strict';
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config.json')[env];
const db = {};
let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
const model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
package.json
{
"name": "my-app-model",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"format": "prettier --write \"src/**/*.{js,jsx,ts,tsx}\"",
"start": "next start",
"type-check": "tsc"
},
"dependencies": {
"#material-ui/core": "^4.8.3",
"#material-ui/lab": "4.0.0-alpha.39",
"mysql": "^2.18.1",
"mysql2": "^2.1.0",
"next": "9.1.7",
"prettier": "^1.19.1",
"react": "16.12.0",
"react-dom": "16.12.0",
"sequelize": "^5.21.7",
"sequelize-cli": "^5.5.1"
},
"devDependencies": {
"#types/node": "^13.1.6",
"#types/react": "^16.9.17",
"#types/react-dom": "^16.9.4",
"typescript": "^3.7.4"
}
}
I believe the immediate solution is to replace __dirname with something like:
const modelsDir = path.resolve(process.cwd(), 'path/to/models')
fs.readdirSync(modelsDir)
.filter(....
Making __dirname work the way we expect is a known issue on next.js:
I expected __dirname to be the absolute path of the file in which getStaticProps is being executed, but instead it is incorrectly resolving as /.
Here's the issue rephrased as a feature request: https://github.com/vercel/next.js/issues/8251
A little background on how this manifested for me in case this helps someone find this solution:
I'm using a mac, but I was having a very similar problem. I am setting up a next.js app with sequelize. After I ran the sequelize-cli to generate the models/index.js that you quote above, I first saw this error:
Error: Cannot find module '/Applications'
Require stack:
- /Users/username/src/mariner-next/node_modules/sequelize/lib/sequelize.js
- /Users/username/src/mariner-next/node_modules/sequelize/index.js
- /Users/username/src/mariner-next/.next/server/static/development/pages/api/graphql.js
- /Users/username/src/mariner-next/node_modules/next/dist/next-server/server/next-server.js
- /Users/username/src/mariner-next/node_modules/next/dist/server/next.js
- /Users/username/src/mariner-next/node_modules/next/dist/server/lib/start-server.js
- /Users/username/src/mariner-next/node_modules/next/dist/cli/next-dev.js
- /Users/username/src/mariner-next/node_modules/next/dist/bin/next
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:981:15)
at Function.Module._load (internal/modules/cjs/loader.js:863:27)
at Module.require (internal/modules/cjs/loader.js:1043:19)
at require (internal/modules/cjs/helpers.js:77:18)
at Sequelize.import (/Users/username/src/mariner-next/node_modules/sequelize/lib/sequelize.js:481:62)
at eval (webpack-internal:///./tnr/lib/models/index.js:60:36)
at Array.forEach (<anonymous>)
at Module.eval (webpack-internal:///./tnr/lib/models/index.js:58:4)
After some head scratching, I realized that __dirname is set to "/" and so fs.readdrSync(__dirname) is returning a list of my root directory.
I've had success using rootrequire (archived in favor of ES6 modules): https://github.com/ericelliott/rootrequire
const root = require('rootrequire'); // project root path
const myLib = require(`${root}/path/to/lib.js`);
I'm trying to deploy my reactjs (first) app on heroku, but i'm getting some trouble to get it online. I have no builds error, but when i try to launch my app i'm getting the "Cannot get /" error.
So on the Heroku logs i'm not getting any errors but only the heroku[routers] info with a 404 satus.
I did verify that my dist folder is not in .gitignore, try to add heroku logger (without success), add some code to package.json, server.json and webpack.config.js (without success).
my package.json (only important part) :
"engines": {
"node": "9.7.0",
"npm": "5.6.0"
},
"dependencies": {
"#material-ui/core": "^3.9.3",
"axios": "^0.17.1",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.9",
"dotenv": "^5.0.0",
"express": "^4.16.2",
"extract-text-webpack-plugin": "^3.0.2",
"faker": "^4.1.0",
"heroku": "^7.24.4",
"html-webpack-plugin": "^2.30.1",
"logger": "0.0.1",
"material-ui": "^0.20.2",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-draggable": "^3.3.0",
"react-img-zoom": "^0.1.0",
"react-magnifier": "^3.0.1",
"react-router-dom": "^5.0.0",
"react-tap-event-plugin": "^3.0.2",
"reactjs-popup": "^1.4.1",
"style-loader": "^0.19.1",
"twilio": "^3.28.0",
"twilio-video": "^1.15.2",
"webpack": "^3.12.0",
"webpack-dev-middleware": "^2.0.4",
"webpack-hot-middleware": "^2.21.0"
},
"scripts": {
"build": "./node_modules/.bin/webpack",
"start": "node server",
"start:prod": "npm run build && node server.js"
},
my webpack.config.js :
const HtmlWebpackPlugin = require("html-webpack-plugin");
const webpack = require("webpack");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const path = require("path");
require("dotenv").config();
var configFunc = function(){
var config = {
devtool: "source-map",
entry: [
__dirname + "/app/app.js"
],
output: {
path: __dirname + "/dist",
filename: "bundle.js",
publicPath: "/"
},
module: {
rules: [
{
test: /\.js$/,
use: "babel-loader",
exclude: [/node_modules/]
},
{
test: /\.(sass|scss|css)$/,
use: [
{
loader: "style-loader" // creates style nodes from JS strings
},
{
loader: "css-loader" // translates CSS into CommonJS
}
]
}
]
},
plugins: [
new HtmlWebpackPlugin({
hash: true,
template: path.join(__dirname , "/app/index.html"),
inject: "body"
}),
new webpack.BannerPlugin("React Twilio"),
new ExtractTextPlugin("[name]-[hash].css")
]};
if(process.env.NODE_ENV === "PROD") {
config.plugins.push(new webpack.optimize.UglifyJsPlugin());
config.plugins.push(new webpack.optimize.CommonsChunkPlugin({
name: "commons",
filename: "commons.js"
}));
}
if(process.env.NODE_ENV === "DEV") {
config.entry.push('webpack-hot-middleware/client?reload=true');
config.plugins.push(new webpack.HotModuleReplacementPlugin());
}
return config;
}();
module.exports = configFunc;
my server.js :
require("dotenv").config();
var path = require("path");
var express = require("express");
var webpack = require("webpack");
var faker = require("faker");
var AccessToken = require("twilio").jwt.AccessToken;
var VideoGrant = AccessToken.VideoGrant;
var app = express();
if(process.env.NODE_ENV === "DEV") { // Configuration for development environment
var webpackDevMiddleware = require("webpack-dev-middleware");
var webpackHotMiddleware = require("webpack-hot-middleware");
var webpackConfig = require("./webpack.config.js");
const webpackCompiler = webpack(webpackConfig);
app.use(webpackDevMiddleware(webpackCompiler, {
hot: true
}));
app.use(webpackHotMiddleware(webpackCompiler));
app.use(express.static(path.join(__dirname, "app")));
} else if(process.env.NODE_ENV === "PROD") { // Configuration for production environment
app.use(express.static(path.join(__dirname, "dist")));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'dist', 'index.html'));
});
}
app.use(function(req, res, next){
console.log("Request from: ", req.url);
next();
})
// Endpoint to generate access token
app.get("/token", function(request, response) {
var identity = faker.name.findName();
// Create an access token which we will sign and return to the client,
// containing the grant we just created
var token = new AccessToken(
process.env.TWILIO_ACCOUNT_SID,
process.env.TWILIO_API_KEY,
process.env.TWILIO_API_SECRET
);
// Assign the generated identity to the token
token.identity = identity;
const grant = new VideoGrant();
// Grant token access to the Video API features
token.addGrant(grant);
// Serialize the token to a JWT string and include it in a JSON
response
response.send({
identity: identity,
token: token.toJwt()
});
});
var port = process.env.PORT || 3000;
app.listen(port, function() {
console.log("Express server listening on *:" + port);
});
and my Procfile :
web: npm run start:prod
You can find my app at this link : https://salty-dawn-74805.herokuapp.com/
For information my app is inspired by this tutorial : https://www.twilio.com/blog/2018/03/video-chat-react.html
You can clone this repository to reproduce : https://github.com/kimobrian/TwilioReact.git
The only error message i get is this (and obviously my website is working well on localhost):
heroku[router]: at=info method=GET path="/" host=salty-dawn-74805.herokuapp.com request_id= fwd= dyno=web.1 connect=1ms service=20ms status=404 bytes=383 protocol=https
Hope someone can help me, i'm new to reactjs and it's the first time i'm deploying a reactjs app.
Thank you very much,
Solution found for others who maybe will have the same error !
It was really stupide : heroku node_env is "production" and i was verifying node_env equals "prod". :'(
I am trying to setup webpack dev server using webpackDevMiddleware, webpackHotMiddleware with express generator and react. I got everything working, but there's a huge delay in the reload.
I will get this message every time in the browser
'GET http://localhost:8080/__webpack_hmr
net::ERR_INCOMPLETE_CHUNKED_ENCODING 200 (OK)'
But 5 to 10 seconds later the browser will reload. In the terminal, these messages are showing
GET /7310e23232f92e879547.hot-update.json 404 6.282 ms - 1573
GET / 304 1.071 ms - -
GET /__webpack_hmr 200 1.767 ms - -
GET /stylesheets/style.css 304 1.306 ms - -
GET /app-bundle.js 200 5.337 ms - 2960039
I think the express server has a delay or stopping from getting the hot-update.json.
I have tried time out and keepAliveTimeout the bin/www file
server.listen(port, () => {
server.timeout = 0
server.keepAliveTimeout = 0
});
package.json
{
"name": "react-webpack-hmr",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www",
"dev": "nodemon ./bin/www --inspect --watch app.js --watch webpack.config.js --watch src",
"build": "webpack --config=webpack.config.js",
"clean": "rimraf public/dist"
},
"dependencies": {
"babel-loader": "^8.0.4",
"cookie-parser": "~1.4.3",
"css-loader": "^2.1.0",
"debug": "~2.6.9",
"ejs": "~2.5.7",
"ejs-loader": "^0.3.1",
"express": "~4.16.0",
"extract-loader": "^3.1.0",
"file-loader": "^3.0.1",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"http-errors": "~1.6.2",
"morgan": "~1.9.0",
"react": "^16.7.0",
"react-dom": "^16.7.0",
"react-hot-loader": "^4.6.3",
"style-loader": "^0.23.1"
},
"devDependencies": {
"#babel/preset-react": "^7.0.0",
"#babel/runtime": "^7.2.0",
"#babel/generator": "^7.2.2",
"#babel/polyfill": "^7.2.5",
"babel-plugin-async-to-promises": "^1.0.5",
"#babel/core": "^7.2.2",
"#babel/plugin-transform-runtime": "^7.2.0",
"#babel/preset-env": "^7.2.3",
"webpack": "^4.28.3",
"webpack-cli": "^3.1.2",
"webpack-dev-middleware": "^3.4.0",
"webpack-dev-server": "^3.1.14",
"webpack-hot-middleware": "^2.24.3"
}
}
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
module.exports = {
entry: {
app: [
'webpack-hot-middleware/client?reload=true',
// 'webpack/hot/only-dev-server',
// 'react-hot-loader/patch',
"#babel/runtime/regenerator",
"./src/app.js"
]
},
mode: 'development',
output: {
filename: "[name]-bundle.js",
path: path.join(__dirname, 'public/dist'),
publicPath: "/"
},
devtool: "cheap-eval-source-map",
devServer: {
contentBase: "dist",
overlay: true,
hot: true
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader'
}
]
},
{
test: /\.html$/,
use: [
{
loader: "html-loader"
}
]
},
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
new HtmlWebpackPlugin({
template: './views/index.ejs'
})
]
}
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const webpack = require("webpack");
const config = require("./webpack.config");
const compiler = webpack(config);
const webpackDevMiddleware = require('webpack-dev-middleware')(compiler, config.devServer);
const webpackHotMiddleware = require('webpack-hot-middleware')(compiler, config.devServer);
var app = express();
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(webpackDevMiddleware);
app.use(webpackHotMiddleware);
//app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
React side app.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App.js';
import { AppContainer } from 'react-hot-loader';
function render(Component) {
ReactDOM.render(
<AppContainer>
<Component />
</AppContainer>,
document.getElementById('app')
)
}
render(App);
if (module.hot) {
module.hot.accept('./components/App', () => {
const newApp = require('./components/App').default
render(newApp);
})
}
I expect the browser will reload after is finished compiling the new code without a delay everytime I save my files.
So I fixed it was my package.json
I was watching the react files which it shouldn't
I removed the old code this is the new one
"dev": "nodemon --inspect --watch webpack.config.js --watch app.js",
TLDR; In order to have hot module reload working with Nodemon you need to exclude the client code from watch.
Webpack uses __webpack_hmr to receive events about changes in code. If you edit a file then save it, Nodemon restarts and in this time Webpack HMR loses connection to the event stream, resulting in a miss for getting updated code. This is the reason why you need to exclude client side code from the watch list of Nodemon. Basically client side code refresh is 'managed' by Webpack dev server.
Usually I have a nodemon.json file in my root to let Nodemon know what to watch:
{
"watch": [
"server.js",
"src/server",
"config"
]
}
I'm trying to build an application using typescript , express . but i'm getting this error :
Cannot invoke an expression whose type lacks a call signature. Type 'typeof e' has no compatible call signatures(in app.ts where express() is called )
I'm using webpack here to help with my development.
My Package.json :
"scripts" :{
"build": "webpack"
},
"dependencies": {
"body-parser": "^1.18.3",
"dotenv": "^6.1.0",
"jsonwebtoken": "^8.3.0",
"nodemon": "^1.18.5"
},
"devDependencies": {
"#types/body-parser": "^1.17.0",
"#types/dotenv": "^4.0.3",
"#types/express": "^4.16.0",
"clean-webpack-plugin": "^0.1.19",
"ts-loader": "^5.3.0",
"ts-node": "^7.0.1",
"typescript": "^3.1.6",
"webpack": "^4.24.0",
"webpack-cli": "^3.1.2"
}
my webpack.confg.js :
var path = require("path");
const CleanWebpackPlugin = require("clean-webpack-plugin");
var fs = require("fs");
var nodeModules = {};
fs.readdirSync("node_modules")
.filter(function(x) {
return [".bin"].indexOf(x) === -1;
})
.forEach(function(mod) {
nodeModules[mod] = "commonjs " + mod;
});
module.exports = {
entry: "./src/index.ts",
plugins: [new CleanWebpackPlugin(["./dist"])],
output: {
filename: "index.js",
path: path.resolve(__dirname, "dist")
},
module: {
rules: [
//all files with .ts extention will be handled y ts-loader
{ test: /\.ts$/, loader: "ts-loader" }
]
},
target: "node",
externals: nodeModules
};
my app.ts :
import * as express from "express";
import * as bodyParser from "body-parser";
class App {
public app: express.Application;
constructor() {
this.app = express();
this.config();
}
private config(): void {
//add support for application/json type for data
this.app.use(bodyParser.json());
//support application/x-www-form-urlencoded post data
this.app.use(bodyParser.urlencoded({ extended: false }));
}
}
export default new App().app;
I'm running npm run build and my build fails with the error stated .
tried searching for solution in a few blogs and none have mentioned tanything about this error .I manged to add express.Application as type for app in side app.ts
What am i doing wrong ? Is it because of the configuration of webpack ?
Any help appreciated
You need to import the default export from express instead of the namespace (which is an object with all named exports).
In your app.ts this should be all you need:
// Change these
import express from "express";
import bodyParser from "body-parser";
The difference is:
// Namespace import
import * as express from "express";
const app = express.default();
// Default import
import express from "express";
const app = express();
For me, it worked on changing the import as-
import { express } from "express";
const app = express();