Vue.js 2 Webpack 3 如何将外部 .js 从 CDN 插入到 webpack 外部? [英] Vue.js 2 Webpack 3 How to insert external .js from CDN into webpack externals?

查看:34
本文介绍了Vue.js 2 Webpack 3 如何将外部 .js 从 CDN 插入到 webpack 外部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们使用像 jQuery 这样的 cdn 库而不是捆绑它时

When we use a cdn library like jQuery instead of bundling it

<script
  src="https://code.jquery.com/jquery-3.1.0.js"
    integrity="sha256-slogkvB1K3VOkzAI8QITxV3VzpOnkeNVsKvtkYLMjfk="
    crossorigin="anonymous">
</script>

我们必须将它作为外部依赖包含进来:

we have to include it as an external dependency :

externals: {
   jquery: 'jQuery'
}

然后在 Vue.component 中要求它

then require it in the Vue.component

import $ from 'jquery';
..
$('.my-element').animate(...);

好的,但是我们如何找到要插入到外部的模块 ID?

OK, but how do we find the module ID to insert into the externals ?

举个例子,如果我使用paypal api checkout.js

As an example, if I use the paypal api checkout.js

<script src="https://www.paypalobjects.com/api/checkout.js"></script>

我需要将它导入到我的组件 vue 中

and I need to import it into my component vue

import paypal from 'paypal'

要在 webpack externals 中写入的模块 id 是什么,我们可以在哪里(如何)从 paypal.js 文件内容中找到它?

What is the module id to write in the webpack externals and where (how) can we find it from the paypal.js file content ?

外部:{贝宝:'结帐'.//或 'paypal-checkout' 或 'paypal' ???},

externals: { paypal: 'checkout'. // or 'paypal-checkout' or 'paypal' ??? },

感谢反馈

推荐答案

SOLVED ... 使用 html-webpack-externals-plugin 包!

SOLVED ... using the html-webpack-externals-plugin package !

yarn add html-webpack-externals-plugin --dev

webpack.dev.conf.js

webpack.dev.conf.js

const HtmlWebpackExternalsPlugin = require('html-webpack-externals-plugin')
...
plugins: [
    ...
    new HtmlWebpackExternalsPlugin({
      externals: [
        {
          module: 'paypal',
          entry: 'https://www.paypalobjects.com/api/checkout.js',
          global: 'paypal'
        }
      ]
    }),
...

index.html

  <script src="https://www.paypalobjects.com/api/checkout.js"></script>

Payments.vue 组件

Payments.vue component

<script>
  ....
  import paypal from 'paypal'

这篇关于Vue.js 2 Webpack 3 如何将外部 .js 从 CDN 插入到 webpack 外部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆