Javascript 将es5库包括到模具web组件中
我有一个旧生活风格的外部图书馆。我有一个web组件,它在内部使用这个库。此web组件是使用模具创建的。 现在,如果我在某个项目中使用我的web组件,我必须通过src文件将组件js文件和这个外部库包含到index.html中。如何将此库包含到组件的编译代码中?是否可以不将其重新写入es6模块 这就是我的代码现在的样子(在index.html中): 这是我的stencil.config.ts:Javascript 将es5库包括到模具web组件中,javascript,typescript,stenciljs,stencil-component,Javascript,Typescript,Stenciljs,Stencil Component,我有一个旧生活风格的外部图书馆。我有一个web组件,它在内部使用这个库。此web组件是使用模具创建的。 现在,如果我在某个项目中使用我的web组件,我必须通过src文件将组件js文件和这个外部库包含到index.html中。如何将此库包含到组件的编译代码中?是否可以不将其重新写入es6模块 这就是我的代码现在的样子(在index.html中): 这是我的stencil.config.ts: import { Config } from '@stencil/core'; export const
import { Config } from '@stencil/core';
export const config: Config = {
namespace: 'mycomponent',
outputTargets:[
{ type: 'dist' },
{ type: 'docs' },
{
type: 'www',
serviceWorker: null // disable service workers
}
]
};
在项目的根目录中,应该有一个stencil.config.ts文件。您可以在其中指定复制任务。您可以在此处阅读如何执行此操作: 正确设置后,将../assets/文件夹复制到生成文件夹中 您需要将所有外部js文件复制到assets文件夹中
在渲染方法中,您可以直接从/assets/引用js文件。经过一些研究,我发现最好的选择是使用stencil.config中的
globalScript
属性
我将我的库添加到“资源”文件夹,然后将以下行添加到我的stencil.config.ts文件中:
globalScript:'src/assets/myMathLib.js'
之后,我可以在组件的代码中使用myMathLib.calculate(this.age)。根据外部库的编写方式,您可以在组件中导入它。你有图书馆的链接吗?
import {Component, Prop} from '@stencil/core';
declare var myMathLib: any;
@Component({
tag: 'my-component',
shadow: true
})
export class MyComponent {
@Prop() name: string;
@Prop() age: number;
render() {
return <div>
The age of {this.name} is: {myMathLib.calculate(this.age)}
</div>;
}
}
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"allowUnreachableCode": false,
"declaration": false,
"experimentalDecorators": true,
"lib": [
"dom",
"es2017"
],
"moduleResolution": "node",
"module": "esnext",
"target": "es2017",
"noUnusedLocals": true,
"noUnusedParameters": true,
"jsx": "react",
"jsxFactory": "h"
},
"include": [
"src",
"types/jsx.d.ts"
],
"exclude": [
"node_modules"
]
}
import { Config } from '@stencil/core';
export const config: Config = {
namespace: 'mycomponent',
outputTargets:[
{ type: 'dist' },
{ type: 'docs' },
{
type: 'www',
serviceWorker: null // disable service workers
}
]
};
globalScript:'src/assets/myMathLib.js'