【问题标题】:Webpack external JS file not defined when loaded in Vue.js 2 component在 Vue.js 2 组件中加载时未定义 Webpack 外部 JS 文件
【发布时间】:2018-08-02 15:21:50
【问题描述】:

我需要在 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] 无法解析异步组件默认值: ReferenceError: iframeresize 未定义

[vue-router] 路由导航时未捕获的错误:

ReferenceError: iframeresize 未定义

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

【问题讨论】:

  • 只是指出,如果使用外部 webpack 插件,则不需要将 script 标签包含在 index.html 中。

标签: javascript webpack vue.js vuejs2 vue-router


【解决方案1】:

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

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'
    }
  ]
}),

【讨论】:

    【解决方案2】:

    我相信这是因为您使用的是“命名”导入。 (例如带大括号)

    如果你要使用大括号,那么命名的导入必须包含一个导出。

    import {foo} from 'foo'
    

    那么 foo.js 应该包含

    export const foo = ...
    

    因此,在您的情况下,您需要使用不带大括号的默认导入,这将自动包含在 export 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();
    

    【讨论】:

      猜你喜欢
      • 2016-11-08
      • 1970-01-01
      • 1970-01-01
      • 2017-03-29
      • 2017-12-28
      • 1970-01-01
      • 2017-11-08
      • 2018-07-22
      • 2016-06-25
      相关资源
      最近更新 更多