2020-11-07 05:16:15
在 Vue 中引入非 ES6 格式的 JavaScript 文件需要根据文件类型(全局脚本或模块)采用不同方式。以下是具体方法和注意事项:
方法 1:通过 <script> 标签引入全局脚本适用于需要在全局作用域执行的脚本(如 jQuery 插件等)。
在 public/index.html 中直接引入文件会直接挂载到 window 对象,全局可用:
<!-- public/index.html --><head> <script src="/path/to/non-es6.js" type="text/javascript"></script></head>在 Vue 组件中动态加载(按需引入)通过 JavaScript 动态创建 <script> 标签:
// 在 mounted 或方法中动态加载mounted() { const script = document.createElement('script'); script.src = '/path/to/non-es6.js'; script.type = 'text/javascript'; document.body.appendChild(script);}适用于导出了 CommonJS/AMD 模块的非 ES6 文件。
情况 1:文件导出 CommonJS 模块若文件使用 module.exports 导出(如 module.exports = { foo: 'bar' }):
// Vue 组件中import nonES6Module from './non-es6.js';export default { data() { return { // 将 CommonJS 模块合并到组件选项中 ...Object.assign({}, nonES6Module) }; }};情况 2:文件导出全局变量若文件直接挂载到 window(如 window.MyLib = { ... }):
// 在组件中直接使用全局变量export default { mounted() { window.MyLib.init(); // 调用全局方法 }};方法 3:配置构建工具(Webpack/Vite)若需通过模块化方式引入,可配置构建工具处理非 ES6 文件。
Webpack 配置在 vue.config.js 中添加 externals 或自定义 loader:
module.exports = { configureWebpack: { module: { rules: [ { test: /.non-es6.js$/, use: 'imports-loader?exports=>undefined' // 处理非模块化文件 } ] } }};Vite 配置在 vite.config.js 中通过 optimizeDeps 处理:
export default { optimizeDeps: { include: ['./path/to/non-es6.js'] }};注意事项作用域问题
全局脚本通过 <script> 引入时,确保在 Vue 组件中使用前已加载完成(可通过 document.readyState 检查)。
模块导出格式
非 ES6 文件需明确导出方式(如 module.exports 或 window 挂载),否则需通过构建工具转换。
TypeScript 支持若使用 TypeScript,需在 shims-vue.d.ts 中声明模块类型:
declare module '*.non-es6.js' { const content: any; export default content;}根据实际需求选择合适方式,确保文件作用域和导出格式与 Vue 项目兼容。