我一定在这里遗漏了一些非常简单的东西,因为我不明白为什么任何人都可以拥有一个功能正常的 angular-cli 应用程序而无法执行以下操作...
上下文
我有一个 Angular 2 应用程序,其中有一个express.js 后端充当 API。我已经从 webpack 切换到 angular-cli 来捆绑我的文件,因为它提供了简单的提前编译。
我没想到的是,Angular-cli 是如此固执己见,它甚至要求我在我的存储库的 Angular 应用程序目录中保存一个 index.html 文件(我之前将其保存在/views 中,以便 express.js 发送给客户端)。
问题
如果我有 node.js 服务器,我正在努力了解如何从 angular-cli 加载输出的 JS 包。考虑以下angular-cli.json
片段:
"apps": [
{
"root": "app",
"outDir": "public/dist",
],
都是我的bundle.js
文件和我的index.html
将在 public/dist
中输出。这意味着我必须更新我的 node.js 路由才能更改:
// Root
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/../views/index.html'));
});
至:
// Root
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/../public/dist/index.html'));
});
现在的问题是我的public/dist/index.html
文件有 <base href="/">
标签,以及以下生成的脚本标签:
<script type="text/javascript" src="inline.bundle.js"></script><script type="text/javascript" src="vendor.bundle.js"></script><script type="text/javascript" src="main.bundle.js"></script>
嗯,显然当我运行我的node.js服务器时,上面的包不会被发现,因为它们不存在于基本href的位置。没有/inline.bundle.js
,因为它位于 /public/dist/inline.bundle.js
。那么,我如何加载我的前端应用程序?
最佳答案
我认为这不起作用,因为它期望绝对路径,而不是相对路径。
res.sendFile(path.join(__dirname + '/../public/dist/index.html'));
您应该以相对方式将所有 dist 服务器从 Express 文件夹指向 /,例如:
app.use('/', express.static('../public/dist'));
app.get('*', (req, res) => {
res.sendFile('index.html', { root: '../public/dist' });
});
关于node.js - 如何使用 angular-cli 加载包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41658880/