vue中怎么引入非es6js文件

vue中怎么引入非es6js文件
最新回答
蘇瑾熙

2020-11-07 05:16:15

在 Vue 中引入非 ES6 格式的 JavaScript 文件需要根据文件类型(全局脚本或模块)采用不同方式。以下是具体方法和注意事项:

方法 1:通过 <script> 标签引入全局脚本

适用于需要在全局作用域执行的脚本(如 jQuery 插件等)。

  1. 在 public/index.html 中直接引入文件会直接挂载到 window 对象,全局可用:

    <!-- public/index.html --><head> <script src="/path/to/non-es6.js" type="text/javascript"></script></head>
  2. 在 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);}
方法 2:通过 import 引入模块化文件

适用于导出了 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'] }};注意事项
  1. 作用域问题

    全局脚本通过 <script> 引入时,确保在 Vue 组件中使用前已加载完成(可通过 document.readyState 检查)。

  2. 模块导出格式

    非 ES6 文件需明确导出方式(如 module.exports 或 window 挂载),否则需通过构建工具转换。

  3. TypeScript 支持若使用 TypeScript,需在 shims-vue.d.ts 中声明模块类型:

    declare module '*.non-es6.js' { const content: any; export default content;}
总结
  • 全局脚本:用 <script> 标签引入(public/index.html 或动态加载)。
  • CommonJS 模块:通过 import + Object.assign 合并到组件选项。
  • 构建工具配置:针对复杂场景(如依赖处理)调整 Webpack/Vite 配置。

根据实际需求选择合适方式,确保文件作用域和导出格式与 Vue 项目兼容。