我需要在 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 {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();
关于javascript - 在 Vue.js 2 组件中加载时未定义 Webpack 外部 JS 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48933118/