【问题标题】:Js file inside node_modules is not accessible to index.htmlindex.html 无法访问 node_modules 中的 Js 文件
【发布时间】:2018-06-27 11:59:27
【问题描述】:

我在玩stencil 到目前为止我做了什么:

  1. 在模板中创建了一个组件
  2. 已将其发布到 npm
  3. 创建了一个角度项目
  4. 已将模板组件安装到 Angular 项目中
  5. 将 component.js 文件添加到 index.html 文件中

当我添加时

<script src="/node_modules/stencil-poc-ng/dist/mycomponent.js"></script>

然后浏览器控制台给出以下错误:

GET http://localhost:4200/node_modules/stencil-poc-ng/dist/mycomponent.js 404(未找到) localhost/:1 拒绝执行来自 'http://localhost:4200/node_modules/stencil-poc-ng/dist/mycomponent.js' 的脚本,因为它的 MIME 类型 ('text/html') 不可执行,并且启用了严格的 MIME 类型检查。

【问题讨论】:

    标签: javascript angular stencils


    【解决方案1】:

    您正在构建一个 Angular 应用程序,它在您的浏览器上运行时将无法访问您计算机上的本地路径。 Angular ng serve做了什么:

    • 将所有代码和依赖项捆绑在一个 HTML 文件、一个 CSS 文件和一堆 JS 文件中
    • 将所有这些文件保存在内存 (RAM) 中
    • 启动 Web 服务器以提供这些文件

    仅提供“内存中”文件,然后您的 http://localhost:4200/node_modules/stencil-poc-ng/dist/mycomponent.js 将始终无效

    你只有两个选择:

    • 导入您的 JS 文件,使其包含在 Angular 构建中
    • 使用&lt;script src='https://unpkg.com/stencil-poc-ng@0.0.1/dist/mycomponent.js'&gt;&lt;/script&gt;

    【讨论】:

    • 感谢您的回复,我之前已经完成了这项工作,但模板文档github.com/ionic-team/stencil-component-starter 说明了我所做的。请查看节点模块部分
    • Stencil 文档没有说明该解决方案在哪种情况下有效。我已经详细解释了为什么这个解决方案与 Angular 不兼容
    • 是的,我不是在抱怨你的回答。我很好奇他们有节点模块部分,他们提到它是为了将它用作节点模块,所以它为什么不工作只是我关心的问题。顺便说一句,感谢您的回答
    • 也许此解决方案适用于为 node_modules 文件夹提供服务的 node.js Web 服务器,老实说,我不知道这种实现的任何可能用例
    【解决方案2】:

    在 Angular 项目中有两种使用模板组件的方法,它们是:

    1. 添加你的js文件的远程路径,例如: https://unpkg.com/{module-name}@{module-version}/dist/{relevant-js-

    2. 将你的js文件添加到assets文件夹,原因是angular查找angular.json或angular.cli.json文件的assets数组中提到的assets。

    感谢@YoukouleleY 提出第一个解决方案并给出我无法访问第二个解决方案的正当理由

    【讨论】:

      猜你喜欢
      • 2017-07-20
      • 1970-01-01
      • 2013-10-02
      • 1970-01-01
      • 2015-10-19
      • 1970-01-01
      • 2016-10-03
      • 1970-01-01
      • 2022-01-21
      相关资源
      最近更新 更多