在 Vue.js 2 组件中加载时未定义 Webpack 外部 JS 文件

Webpack external JS file not defined when loaded in Vue.js 2 component

我需要在 Vue.js 组件中包含来自外部 JS 文件的函数。我参考了 this answer 来弄清楚如何在我的 webpack 配置中加载外部文件。我当前的设置如下所示:

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

import { iFrameResize } from 'iframeresize'

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

但是,我现在从 vue-router 收到一个错误。

[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

从外部文件加载函数时我是否遗漏了一个步骤?当直接从 index.html 加载时,我可以使用该函数,但随后我收到一个警告,该函数未定义,因为我的 webpack 配置似乎被忽略了。

一个问题可能是导入表达式,更改为:

import iFrameResize from 'iframeresize'

更新:刚刚重现了问题,上面的导入工作正常。

注意 还记得在实例化 html-webpack-plugin 之后实例化插件 HtmlWebpackExternalsPlugin(参见 Usage section of the docs

这是我用过的插件配置(更改全局选项值):

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

我相信这是因为您正在使用 "named" 导入。 (例如带大括号)

如果您要使用大括号,则指定的导入必须包含导出。

import {foo} from 'foo'

那么 foo.js 应该包含

export const foo = ...

因此,在您的情况下,您需要使用不带大括号的默认导入,这将自动包含在 export default 语句中。

只需使用 'default' 导入语法。

import foo from 'foo'

并不是那么重要,只是为了帮助理解,默认导入实际上可以通过使用特殊名称 default

用大括号导入
import { default as foo } from 'foo'; 

此外,如果一个模块中有多个命名导出,您可以将它们全部导入,然后通过 属性 引用它们。

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

//reference the named exports later with.. 

foo.doThis();
foo.doThat();