所以看来我的做法是错误的。我的情况的简短答案是使用 gulp 将 dist 目录中的文件通过管道传输到另一个目录以进行部署和管道服务器文件。如果有人感兴趣,这里是完整的工作流程:
开发中
所有服务器文件都进入 angular-cli 生成的 src 目录。我将服务器目录用于模型、路由等,并将 app.js 文件用作应用程序的入口点。当从命令行运行 ng build 时,这些文件将被添加到 dist 目录。所以 app.js 文件将指向 index.html。这是一个简单的例子:
// app.js
var express = require('express');
var app = express();
var router = express.Router();
var port = process.env.PORT || 3000;
router.get('/*', function (req, res) {
res.sendfile(path.join(__dirname, "index.html"));
});
app.listen(port, function () {
console.log('Express server started on port ' + port);
});
module.exports = app;
您可以从命令行运行 ng build 或 ng test,这会将服务器文件添加到 dist 目录。要运行应用程序,请从命令行使用 node dist/app。
生产中
当使用 ng build -production 为生产构建时,src 目录中的服务器文件不会移动到 dist 目录中。所以我使用 gulp 创建一个新目录,添加 dist 目录中的文件和 src 目录中的服务器文件。我不擅长任务运行器,所以这里是完整的代码:
从命令行:npm install --save-dev gulp del
将 gulpfile.js 添加到应用程序根目录。
// gulpfile.js
var gulp = require('gulp');
var del = require('del');
// destination for piped files
var deployment = 'heroku';
// remove old files from the deployment directory
gulp.task('clean', function() {
del([ (deployment + '/**/*'), '!.git']);
});
// grab the angular files
gulp.task('angularFiles', function() {
return gulp.src('dist/**/*')
.pipe(gulp.dest(deployment));
});
// grab the server files and package.json
gulp.task('packageFile', function() {
return gulp.src('package.json')
.pipe(gulp.dest(deployment));
});
gulp.task('serverFiles', function() {
return gulp.src('src/server/**/*')
.pipe(gulp.dest(deployment + '/server'));
});
gulp.task('appFile', function() {
return gulp.src('src/app.js')
.pipe(gulp.dest(deployment));
});
// make a single task for the npm script
gulp.task('buildProd', ['angularFiles','packageFile','serverFiles','appFile']);
在 package.json 文件中,新建一个脚本:"build:heroku": "gulp clean && ng b -prod && gulp buildProd"
这会运行 gulp 任务并使用 angular ng b -prod 命令,该命令为生产而构建。
在命令行中使用npm run build:heroku运行应用程序根目录下的脚本
第一次运行脚本时,它将创建部署目录(在我的例子中称为 heroku),清理它,添加角度文件,然后添加服务器文件和 package.json。由于我不是任务运行专家,我手动做的一件事是从 heroku 目录中删除多余的脚本,所以它看起来像这样:
// heroku/package.json
"scripts": {
"start": "node app.js",
}
否则,heroku 可能会在部署期间尝试运行其他一些 angular npm 脚本。
然后我 cd 进入 heroku 目录并使用 git 进行部署。从命令行:
git init // only for first deployment
git add -A
git commit -m 'ready for deployment'
heroku create // only for first deployment
-or-
heroku git:remote -a <heroku app name> // only for first deployment
git push heroku master
对于后续部署,npm 脚本 build:heroku 不会删除 git 存储库。只需运行脚本,调整 package.json,然后使用 git 推送到 heroku。
其他几件事
- 记得将部署目录添加到主应用程序的 .gitignore 文件中。
- 我发现 Dropbox 有时会与 ng build -production 发生冲突。暂停 Dropbox 同步可解决此问题。
- angular-cli
ng build 或 ng build -production 每次都会重写 dist 文件夹。所以部署后,你必须重建开发环境。我个人使用 ng test 并让它在终端中运行。