1
votes

I need to include a function from an external JS file in a Vue.js component. I've referenced this answer to figure out how to load the external file in my webpack config. My current setup looks like this:

webpack.dev.conf.js

const HtmlWebpackExternalsPlugin = require('html-webpack-externals-plugin')

[...]

new HtmlWebpackExternalsPlugin({
  externals: [{
    module: 'iframeresize',
    entry: 'https://[...]/iframeResizer.min.js',
    global: 'iframeresize'
  }]
})

index.html

<script src="https://[...]/iframeResizer.min.js"></script>  

.vue component

import { iFrameResize } from 'iframeresize'

export default {
  name: 'FMFrame',
  mounted () {
    iFrameResize()
  }
}

However, I'm getting an error from vue-router now.

[vue-router] Failed to resolve async component default: ReferenceError: iframeresize is not defined

[vue-router] uncaught error during route navigation:

ReferenceError: iframeresize is not defined

Is there a step I'm missing in loading the function from the external file? I can use the function when loaded directly from index.html, but then I get a warning that the function is undefined as my webpack config seems to be ignored.

2
Just to point out that if the external webpack plugin is used it is not necessary to include the script tag into index.html.attdona

2 Answers

3
votes

I believe this is happening because you are using a "named" import. (e.g. with braces)

If you are going to use braces then the the named import must contain an export.

import {foo} from 'foo'

then foo.js should contain

export const foo = ...

So in your case you need to use a default import without the braces which will automatically get included in the export default statement.

Simply use the 'default' import syntax.

import foo from 'foo'

Not really all that important but just to help understanding, a default import can actually be imported with braces by using the special name default

import { default as foo } from 'foo'; 

Further if a module has several named exports in it you can import them all and then refer to them by property.

import * as foo from 'bar'; // has two named exports doThis and doThat

//reference the named exports later with.. 

foo.doThis();
foo.doThat();
0
votes

One problem could be the import expression, change with:

import iFrameResize from 'iframeresize'

UPDATE: just reproduced the problem and the above import works correctly.

NOTE Also remember to instantiate the plugin HtmlWebpackExternalsPlugin after your instance of html-webpack-plugin (see the Usage section of the docs)

this is the plugin configuration that I've used (change the global option value):

new HtmlWebpackExternalsPlugin({
  externals: [
    {
      module: 'iframeresize',
      entry: 'https://<url_path>/iframeResizer.js',
      global: 'iFrameResize'
    }
  ]
}),