一、在 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  之后重启编辑器即可解决。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。