[英]How to import external JavaScript into Polymer 3.0
Let's say I have a traditional javascript library such as google-charts and I wanted to incorporate that into my Polymer 3.0 project.假设我有一个传统的 javascript 库,例如 google-charts,我想将它合并到我的 Polymer 3.0 项目中。 How would I actually do the import?
我实际上将如何进行导入?
This is how I would traditionally do it: https://developers.google.com/chart/interactive/docs/quick_start这就是我传统上的做法: https : //developers.google.com/chart/interactive/docs/quick_start
Normally, one would prefer an ES module version of such a library if available (eg, on NPM ), since ES modules allow tree shaking (by Polymer CLI in this case) to reduce the size of the production build output.通常,如果可用(例如,在NPM 上),人们会更喜欢此类库的 ES 模块版本,因为 ES 模块允许摇树(在这种情况下通过Polymer CLI )以减少生产构建输出的大小。
Modules are loaded in JavaScript with the import
keyword.模块在 JavaScript 中使用
import
关键字加载。 If available on NPM, the library could be installed in your Polymer project with the npm-install
command.如果在 NPM 上可用,则可以使用
npm-install
命令将该库安装在您的 Polymer 项目中。 For instance, you'd install google-charts
like this:例如,您可以像这样安装
google-charts
:
npm install --save google-charts
Then, import that package in your element code:然后,在您的元素代码中导入该包:
import { GoogleCharts } from 'google-charts';
Example:例子:
import { PolymerElement } from '@polymer/polymer';
import { GoogleCharts } from 'google-charts';
class MyElement extends PolymerElement {
// ...
ready() {
super.ready();
GoogleCharts.load(/* ... */);
}
}
On the other hand if ESM is unavailable, the script is likely an AMD/UMD module, which adds symbols to the global scope.另一方面,如果 ESM 不可用,则脚本很可能是 AMD/UMD 模块,它将符号添加到全局范围。 In that case, you'd still
import
the file, and access the global as you normally would had you used the <script>
tag.在这种情况下,您仍将
import
文件,并像通常使用<script>
标记一样访问全局。
If the script is not on NPM, you'd have to copy the file locally into your project (and include the library file in your release), and then import the file by path.如果脚本不在 NPM 上,您必须将文件本地复制到您的项目中(并在您的版本中包含库文件),然后按路径导入文件。 For example, if you copied the library to
<root>/src/libs/google-charts.js
, the element code at <root>/src/components/Chart.html
would import it like this:例如,如果复制的库
<root>/src/libs/google-charts.js
,在元件代码<root>/src/components/Chart.html
将其导入这样的:
import '../libs/google-charts'
Example:例子:
import { PolymerElement } from '@polymer/polymer';
import '../libs/google-charts' // adds GoogleCharts to global
class MyElement extends PolymerElement {
// ...
ready() {
super.ready();
GoogleCharts.load(/* ... */);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.