Vue 项目中引入本地第三方 JS 库

一、在 inde.html 中使用 script 标签来引入

1、直接引入,全局可用

ESLint 语法检测会报错:'$' is not define

// index.html

<script src="./static/jquery.js"></script>
// vue文件

export default {

    mounted () {
      /* eslint-disable */
      console.log($)
    }

}

2、在 webpack 中配置一个 externals,使用import来引入使用

ESLint 语法检测不会报错

// index.html

<script src="./static/jquery.js"></script>
// webpack配置文件

externals: {
  'jquery': 'jQuery'
}
// vue文件

import $ from 'jquery'
 
export default {

  mounted () {
    console.log($)
  }

}

二、在webpack中配置 alias来引入

1、使用 import 引入使用

ESLint 语法检测不会报错

// webpack 配置文件

resolve: {
  extensions: ['.js', '.vue', '.json'],

  alias: {
    '@': resolve('src'),
    'jquery': resolve('static/jquery.js')
  }
}
// vue文件

import $ from 'jquery'

export default {

  mounted () {
    console.log($)
  }

}

2、不用import,但需在 webpack 配置 plugins

ESLint 语法检测会报错:'$' is not define

// webpack配置文件

resolve: {
  extensions: ['.js', '.vue', '.json'],

  alias: {
    '@': resolve('src'),
    'jquery': resolve('static/jquery.js')
  }
},

plugins: [
  new webpack.ProvidePlugin({
    $: 'jquery'
  })
]
// vue文件

export default {

  mounted () {
    /* eslint-disable*/
    console.log($)
  }

}

三、解决ESLint报错

项目开启了 ESLint 语法检测的话,会报一个 error :'$' is not defined。

1、在每一个使用 $ 的代码行上加 /* eslint-disable */ ,忽略该报错。

2、在根目录下的 .eslintrc.js 的rules{}中添加  'no-undef': 0  之后重启编辑器即可解决。

猜你喜欢

转载自blog.csdn.net/qq_31851435/article/details/129556445