【问题标题】:Vue.js 2 Webpack 3 How to insert external .js from CDN into webpack externals?Vue.js 2 Webpack 3 如何将外部 .js 从 CDN 插入 webpack 外部?
【发布时间】:2018-07-22 09:05:11
【问题描述】:

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

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

我们必须将其作为外部依赖项包含在内:

externals: {
   jquery: 'jQuery'
}

然后在 Vue.component 中要求它

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

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

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

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

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

import paypal from 'paypal'

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

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

感谢反馈

【问题讨论】:

    标签: webpack vue.js


    【解决方案1】:

    已解决...使用 html-webpack-externals-plugin 包!

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

    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 组件

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

    【讨论】:

    • 只是指出,如果使用外部 webpack 插件,则不需要将 script 标签包含在 index.html 中
    • 有人在vue-cli3.x中使用html-webpack-externals-plugin吗,我发现这个插件会在html文件中多次插入我的外部文件
    【解决方案2】:

    html-webpack-externals-plugin好久没更新了,有bug
    如果有人在使用第三方库,例如“http://somedomain/plugin.js”(不是cdn),您可以使用html-webpack-tags-plugin。它的旧名称是 html-webpack-include-assets-plugin,它依赖于 html-webpack-externals-plugin
    我在多页的 vue-cli3.x 中使用,一切正常。
    示例

        plugins: [
          new HtmlWebpackTagsPlugin({
            append: false, // append first
            publicPath: false, // remote lib doesn't use publicPath
            tags: [http://somedomain/plugin.js]
          })
        ]
    

    【讨论】:

      猜你喜欢
      • 2017-10-24
      • 2019-03-20
      • 2018-09-24
      • 1970-01-01
      • 1970-01-01
      • 2018-11-11
      • 1970-01-01
      • 2018-08-02
      • 2017-05-13
      相关资源
      最近更新 更多