Why can't export/import const app = express to another js file

I am trying to separate responsibilities, dividing in different files and modules the different actions that I will carry out in my application on the server side.

I ran into a problem, which I can not understand. I try to export from the file which starts the server, the variable app, in which I store express in the following way:

server.js

import express from 'express';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackConfig from '../webpack.config';
import path from 'path';

const app = express();

app.set('port', process.env.PORT || 3000);

app.use(webpackDevMiddleware(webpack(webpackConfig)));

app.get('*', (req, res) => { 
    res.sendFile(path.join(__dirname, '..', 'public', 'index.html'));
});

app.get('/api', (req, res) => {
    res.json({api: "Woks Fine"});
});

app.listen(app.get('port'), () => {
    console.log("App Start in Port", app.get('port'));
});

export default app;

apiGoogleMaps.js

import app from '../server.js';

export function respuestaMensaje(apiUrl, app) {
    console.log(apiUrl);
    app.post(apiUrl, (req, res) => {
        console.log(req.body);
    });
}

adressjs

import React, { Component } from 'react';
import { render } from 'react-dom';
import request from 'superagent';
import { respuestaMensaje } from '../../../src/handlers/apiGoogleMap.js';


class AddressInput extends Component{

    constructor(){    
        super();
        this.state = {
            address: "",
            api:"http://maps.google.com/maps/api/geocode/json?address=",
            direccion: "",
            latitud: "",
            longitud:""
        };
    } 

    render(){
        return(
            <div> 

                <form>                
                    <input type="text" value={this.state.address} onChange={this.updateAdress.bind(this)}/>
                    <button onClick={this.getAddressGeo.bind(this)}>Consultar</button> 
                </form>

                <ul>
                    <li><label>Direccion:</label>{this.state.direccion}</li>
                    <li><label>Latitud:{this.state.latitud}</label></li>
                    <li><label>Longitud:{this.state.longitud}</label></li>
                </ul>
            </div> 
        )
    }

    updateAdress(event){
        this.setState({
            address: event.target.value
        });
    }

    getAddressGeo(e){

        e.preventDefault();
        const apiUrl = this.state.api + this.state.address;
        respuestaMensaje(apiUrl);
    } 
}

export default AddressInput;

Project Structure

image

Many errors like this appear:

[1] WARNING in ./node_modules/uglifyjs-webpack-plugin/node_modules/uglify-es/tools/node.js
[1] 18:11-32 Critical dependency: the request of a dependency is an expression
[1]  @ ./node_modules/uglifyjs-webpack-plugin/node_modules/uglify-es/tools/node.js
[1]  @ ./node_modules/uglifyjs-webpack-plugin/dist/uglify/minify.js
[1]  @ ./node_modules/uglifyjs-webpack-plugin/dist/uglify/index.js
[1]  @ ./node_modules/uglifyjs-webpack-plugin/dist/index.js
[1]  @ ./node_modules/uglifyjs-webpack-plugin/dist/cjs.js
[1]  @ (webpack)/lib/WebpackOptionsDefaulter.js
[1]  @ (webpack)/lib/webpack.js
[1]  @ ./src/server.js
[1]  @ ./src/handlers/apiGoogleMap.js
[1]  @ ./src/ui/components/address.js
[1]  @ ./src/ui/app.js
[1]  @ ./src/ui/index.js
[1]

Full error log

Upvotes: 1

Views: 4153

Answers (2)

ssube
ssube

Reputation: 48247

This error is caused by the webpack import in server.js, used as middleware:

import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackConfig from '../webpack.config';
import path from 'path';

const app = express();

app.set('port', process.env.PORT || 3000);

app.use(webpackDevMiddleware(webpack(webpackConfig)));

The telling frames from the stack trace are:

[1]  @ (webpack)/lib/WebpackOptionsDefaulter.js
[1]  @ (webpack)/lib/webpack.js
[1]  @ ./src/server.js

It appears you can't include webpack in a webpack bundle, at least not by importing it, thanks to the dynamic imports that webpack uses.

The same errors appear with express (specifically express.view), explained in this issue:

There's a dynamical requirement in ExpressJS: https://github.com/expressjs/express/blob/master/lib/view.js#L78

You can mark express (and/or webpack) as an external dependency to prevent them from being included in the bundle (I have not used this library, it is linked from the issue).

Upvotes: 2

Geet Choubey
Geet Choubey

Reputation: 1077

Instead of exporting your app, which the main backbone of your entire server, use a router in your apiGoogleMaps.js file and export it.

Use the router in your app.js file successfully! :D

birds.route.js

var express = require('express')
var router = express.Router()

router.get('/', function (req, res) {
    res.send('Birds home page')
})
router.get('/:id', function (req, res) {
    res.send(req.params.id);
    })
module.exports = router

app.js

const myBirds = require('./birds');
...
...
app.use('/birds', myBirds);

Upvotes: 0

Related Questions