简体   繁体   中英

What is the best way to use npm for my front end package manager in a Node.js app?

I'm just learning Node.js and Express with the plan to use Angular for the frontend. I'm using npm for the Node.js modules but I'd also like to use npm for my frontend dependencies. All the tutorials I can find use Bower for the frontend libraries. What's the recommended way to use npm for both?

I currently have the Angular app running in a public folder which I've setup as a static folder using express.static. I have the frontend dependencies also installed in the root node_modules folder and package.json. For the Angular app to access the libraries in there, I have node_modules also setup as a static directory. This doesn't feel right somehow.

Is it a good idea to have two package.json files? One in the root and one in the public folder? Or is there a way to tell npm to install some libraries in the root and some in the public folder (maybe a lib sub-folder)?

Here's my Node app code:

var express = require('express');

var app = express();

var port = 3000;

app.use(express.static('public'));
app.use(express.static('node_modules'));

app.get('/', function(req, res) {
    res.send('Hello world');
});

app.listen(port, function(err) {
    console.log('Running server on port ' + port);
});

And my Angular app code for what it's worth:

<html>
<header>
    <title>My Test Site</title>
    <script src="angular/angular.min.js"></script>
    <script>
        angular.module('MyApp', [])
            .controller('MyController', [function () {
                var ctrl = this;

                // Properties
                ctrl.myTitle = "My Angular App";
            }]);
    </script>
</header>

<body ng-app="MyApp" ng-controller="MyController as myctrl">
    <h2>Welcome to {{ myctrl.myTitle }}</h2>
</body>

</html>

Based on mh-cbon's comments above I've separated my npm dependencies into two package.json files, one in the root for the Node/server side and one in the public folder for the Angular/ui side. Installing each is handled through the build process. This actually worked out really well as I'm planning on separating the server side into a Docker image. Since the two pieces are separate I can easily use a Docker volume to work on my Angular code external to the container.

The only change to the Node app is to remove the static call on node_modules:

var express = require('express');

var app = express();

var port = 3000;

app.use(express.static('public'));

app.get('/', function(req, res) {
    res.send('Hello world');
});

app.listen(port, function(err) {
    console.log('Running server on port ' + port);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM