Search code examples
stenciljs

How to fetch data from a local JSON file in StencilJS?


I am learning stencilJS and wanted to fetch a JSON file from the local path. However, I am not able to do that until I have placed this file in www folder of the app. Problem is whenever I build my application file gets deleted/removed from the folder. I wanted to access this file from a services folder from my app. Kindly find below is my file structure and code.

src > services > mock.json

componentWillLoad() {
  return fetch("./services/mock.json")
    .then(response => response.json())
    .then(data => {
      this.mockData = data;
   });
}

config file

    import { Config } from '@stencil/core';
// import { sass } from '@stencil/sass';

export const config: Config = {
  namespace: 'mycomponent',
  globalStyle: 'src/globals/app.css',
  outputTargets:[
    { type: 'dist' },
    { type: 'docs' },
    {
      type: 'www',
      serviceWorker: null // disable service workers
    }
  ],
  plugins: [
    // sass()
  ]
};

Thank you in advance.


Solution

  • try to add below step in your config file.

    copy: [
        { src: 'services' }
      ]
    

    it will copy the entire directory from src/services over to www/services