Node.js应用程序部署在heroku中
我有我的MEAN应用程序的以下文件结构:
root |---> public |----> css |----> js |----> controller |----> app.js |----> views |----> index.html |---> app |----> server.js |---> node_modules |---> bower_components |---> gulpfile.js |---> package.json |---> Procfile
在这个应用程序中,我使用gulp
运行public/index.html
,
gulpfile.js :
var gulp = require('gulp'); var browserSync = require('browser-sync'); var server = require('gulp-live-server'); gulp.task('server', function() { live = new server('app/server.js'); live.start(); }) gulp.task('serve', ['server'], function() { browserSync.init({ notify: false, port: process.env.PORT || 8080, server: { baseDir: ['public'], routes: { '/bower_components': 'bower_components' } } }); gulp.watch(['public/**/*.*']) .on('change', browserSync.reload); });
然后使用REST API
与app
通信。 这是在本地机器上工作。 我已经把这个项目上传到了heroku
。
我的Procfile :
web: node node_modules/gulp/bin/gulp serve
但它显示错误。 我有以下错误到heroku logs
2017-05-21T16:26:57.305350+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=myapp.herokuapp.com request_id=some-request-id fwd="fwd-ip" dyno= connect= service= status=503 bytes= protocol=https
2017-05-21T15:53:50.942664+00:00 app[web.1]: Error: Cannot find module '/app/node_modules/gulp/bin/gulp'
我的package.json
文件:
{ "name": "myapp", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "gulp serve" }, "repository": { "type": "git", "url": "" }, "dependencies": { "async": "^2.4.0", "body-parser": "^1.17.2", "express": "^4.15.3", "mongoose": "^4.10.0", "morgan": "^1.8.1", "multer": "^1.3.0", "underscore": "^1.8.3" }, "devDependencies": { "browser-sync": "^2.18.11", "gulp": "^3.9.1", "gulp-live-server": "0.0.30" } }
任何build议? 提前致谢。
您可能已经在package.json
文件devDepenenies
定义为开发依赖项(在devDepenenies
下)。 当NODE_ENV
未设置为production
时,NPM仅安装devDependencies
。
当你部署到heroku, NODE_ENV=production
,所以从来没有安装NODE_ENV=production
。 因此,错误…
Error: Cannot find module '/app/node_modules/gulp/bin/gulp'
只需将devDependencies
和从devDependencies
到dependencies
所需的其他任何东西都devDependencies
即可。 你可以让npm把它移动给你..
npm uninstall --save-dev gulp npm install --save gulp
对构build您的包所需的每个开发依赖项重复此操作。 或者你可以自己复制和粘贴。
这是一个没有理想解决schemeAFAIK的常见问题。 NPM期望在生产中,您将已经预先build立了您的文件。 就像你将它们发布到NPM一样。 但是,在heroku和其他推动部署解决scheme,情况并非如此。
查理·马丁 ( Charlie Martin )对dev-dependencies
和--production
标志是正确的(Heroku正确地通过了这个标志)。 您可以在nodejs文档中看到npm install
和package.json的 更多解释 – 这个问题已经在其他地方详细阐述过了 。
不过,我强烈build议部署时不要通过gulp来运行服务任务 ,而是定义npm脚本 start
运行browserSync的CLI 。 这样, 你可以保持一个dev的依赖 。
它可能看起来像这样: package.json
{ ... other properties ... "scripts": { "start": "browser-sync start --port 8080 -s" }, ... other stuff ... }
Browsersync的文档是相当不错的,所以你应该find你所需要的。 我会在当地摆弄它,直到npm start
, gulp serve
做同样的事情,然后我会用heroku部署,看看它是否工作。