Vue.js 2 Webpack 3 How to insert external .js from

2019-03-30 21:33发布

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'
}

then require it in the Vue.component

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

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

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

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

and I need to import it into my component vue

import paypal from 'paypal'

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

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

thanks for feedback

1条回答
冷血范
2楼-- · 2019-03-30 21:56

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

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 component

<script>
  ....
  import paypal from 'paypal'
查看更多
登录 后发表回答