简体   繁体   中英

StencilJS | Importing a third party script in a component

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 .

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM