3

I am trying to use a third party script in a Stencil component which I copied into the build directory. I intend on using stand alone components on various websites. I am not building a Stencil app.

stencil.config.ts

export const config: Config = {
  namespace: 'community-component',
  outputTargets: [
    { type: 'dist' },
    { type: 'docs' },
    {
      type: 'www',
      serviceWorker: null // disable service workers
    }
  ],
  copy: [
    { src: 'www/assets/myscript.js', dest: 'assets/js/myscript.js' }
  ]
};

Then I import it like this, which is not correct. myscript.js also loads jQuery.

import * as MyScript from '../../../src/www/assets/myscript.js';
declare const jQuery: any;

Now I get Uncaught ReferenceError: jQuery is not defined.

Ciprian
  • 3,066
  • 9
  • 62
  • 98
  • 1
    This should be handled same as explained in this question. https://stackoverflow.com/questions/54991630/how-to-fetch-data-from-a-local-json-file-in-stenciljs/55009819#55009819 – Ritesh Singh Rajput Mar 26 '19 at 10:36

1 Answers1

1

In order to use custom scripts in a stencil component, follow these steps:

  1. Create an assets directory in src if it does not exist.
  2. Create a new file and paste the contents of your script or just copy and paste your script file.
  3. Import the script in your tsx file like this:

    import * as myScript from './assets/my-script.js'

  4. Build your component and run.

P.S. - you need not to mention assets folder in copy property of stencil.config.ts. It gets copied by default.

Prasheel
  • 985
  • 5
  • 22