Js file inside node_modules is not accessible to index.html

4.3k Views Asked by At

I am playing with stencil What I have done so far:

  1. Created a component in stencil
  2. Published it to the npm
  3. Created a angular project
  4. Installed stencil component to the angular project
  5. Added component.js file to the index.html file

When I am adding

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

then brower console giving the following error:

GET http://localhost:4200/node_modules/stencil-poc-ng/dist/mycomponent.js 404 (Not Found) localhost/:1 Refused to execute script from 'http://localhost:4200/node_modules/stencil-poc-ng/dist/mycomponent.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

2

There are 2 best solutions below

4
Guerric P On BEST ANSWER

You are building an Angular app, it won't be able to access a local path on your computer when running on your browser. What Angular ng servedoes:

  • Bundle all of your code and dependencies in a HTML file, a CSS file and a bunch of JS files
  • Save all of these files in memory (RAM)
  • Launch a web server to serve these files

Only the "in memory" files are served, then your http://localhost:4200/node_modules/stencil-poc-ng/dist/mycomponent.js will always be invalid

You have only two options left:

  • Import your JS file so that it is included in Angular build
  • Use <script src='https://unpkg.com/[email protected]/dist/mycomponent.js'></script>
0
Lalit Kushwah On

There are two ways to use stencil component on the Angular project and here they are:

  1. Add remote path of your js file, for example: https://unpkg.com/{module-name}@{module-version}/dist/{relevant-js-

  2. Add your js file to the assets folder, reason is angular finds the assets which are mentioned in the assets array of angular.json or angular.cli.json file.

Thanks @YoukouleleY for suggesting the first solution and for giving a proper reason why I am not able to access the second one