电子与Angular中的实时模式一起不加载node_module资源

时间:2017-10-24 18:31:12

标签: javascript angular electron angular-cli vmware-clarity

上下文

我正在使用Angular CLI编写Electron和Angular 2+的应用程序。我已经设置了我的电子.js文件,指向ng serve命令提供的URL,通常是localhost:4200,以捕获代码更改。一些注意事项:

  • 地址localhost:4200指向index.html;
  • index.js是我的电子入口点脚本

这是我的index.js文件,用作电子模块的入口点。

const {app, BrowserWindow} = require('electron');
const url = require('url');
const path = require('path');

let win = null;

function createWindow() {
  win = new BrowserWindow({width: 1000, height: 600, show: false});
  win.loadURL('http://localhost:4200');

  win.maximize();
  win.on('closed', () => {
    win = null;
  });
  win.on('ready-to-show', () => {
    win.show();
  });
  win.webContents.openDevTools();
}

app.on('ready', () => {
  createWindow();
});

app.on('activate', () => {
  if (win === null) {
    createWindow();
  }
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

我的index.html文件:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>BRISA Carbon</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <!--Clarity Design Elements-->
  <link rel="stylesheet" href="../node_modules/clarity-icons/clarity-icons.min.css">
  <script type="text/javascript" src="../node_modules/@webcomponents/custom-elements/custom-elements.min.js"></script>
  <script type="text/javascript" src="../node_modules/clarity-icons/clarity-icons.min.js"></script>
</head>
<body>
  <app-root></app-root>
</body>
</html>

我的问题

当我运行ng serve时,.html文件中的node_modules资源未加载,Chrome控制台会输出以下消息

enter image description here

我知道资源的路径是正确的,因为我正在使用WebStorm IDE,我可以通过下面的链接转到引用的元素。

enter image description here

为什么我在Angular live模式下运行时没有加载我的资源?

2 个答案:

答案 0 :(得分:2)

对于遇到同样问题的每个人,我都找到了解决方案。我没有通过index.html文件加载资源,而是将它们放在.angular-cli.json中。基本上,Angular 2+有自己的导入资源的方式,似乎从主.html文件加载资源是不正确的。

嗯,对于脚本(我的意思是.js文件),我将它放在scripts数组中的styles数组和样式中。我已更改的.angular-cli.json文件部分如下所示:

  "styles": [
    "styles.css",
    "../node_modules/clarity-icons/clarity-icons.min.css",
    "../node_modules/clarity-ui/clarity-ui.min.css"
  ],
  "scripts": [
    "../node_modules/@webcomponents/custom-elements/custom-elements.min.js",
    "../node_modules/clarity-icons/clarity-icons.min.js"
  ]

希望这些信息能够帮助别人。对我来说一切都很好。

答案 1 :(得分:0)

我假设您在浏览器中访问localhost:4200时遇到同样的问题?

在index.html中,您引用的是../node_modules/ ...,它在您的IDE中有效,因为这就是文件夹结构的样子。

假设您的文件夹结构如下所示:

node_modules/
src/

src是您的服务器以root身份使用的文件夹。然后服务器将无法从..检索文件(因为根目录没有父目录)。

您应该在其他JS文件中导入/要求它们,而不是引用index.html中的JS文件。具体如何,你的构建/捆绑工具(例如Webpack和/或Babel)就是如此。

import '@webcomponents/custom-elements/custom-elements.min.js'
import 'clarity-icons/clarity-icons.min.js'
import 'clarity-icons/clarity-icons.min.css' // Assumes that you use webpack and webpack-css-loader, for example