1. Background

Requirements: List reconstruction, need to be part of the online. The new module uses VUE technology stack, and the old module uses jquery technology stack. Therefore, you need to use older versions of jquery in the existing VUE technology stack. To avoid later importing jquery in every file, you want to be able to use jquery as $without importing it anywhere in your project.

2. The role of ProvidePlugin

NPM install jquery NPM install jquery NPM install jquery Import $from ‘jquery’ or const $= require(‘jquery’). You can use jquery without importing it in your file. The parser must be able to recognize jquery. Therefore, it must be identified as jquery through a mode-in-mode mechanism. Therefore, it must be identified as jquery through a mode-in-mode mechanism. Therefore, it is necessary to have the same characteristics as Window through in-mode mechanism. Since the project is packaged based on WebPack, WebPack provides the ProvidePlugin plug-in. What it does is

Automatically load modules instead of having to import or require them everywhere.

3. Configuration of ProvidePlugin

  new webpack.ProvidePlugin({
    '$': 'jquery',
    'jquery': 'jquery',
    'jQuery': 'jquery',
    'window.jQuery': 'jquery',
  }),
Copy the code

Jquery is introduced without import or require. When $is used as $(‘#calendar’). The parser first looks for the jquery directory in the current path. If not, go to node_modules and look for jquery. Of course, to avoid unnecessary searching, or your jquery is stored in a special directory in your current project, such as libs, instead of NPM install. Then you need to display the specified path. For example, jquery is placed in the libs directory under the root path.

  new webpack.ProvidePlugin({
    '$': path.resolve(__dirname, 'libs/jquery.js'),
    'jquery': path.resolve(__dirname, 'libs/jquery.js'),
    'jQuery': path.resolve(__dirname, 'libs/jquery.js'),
    'window.jQuery': path.resolve(__dirname, 'libs/jquery.js'),
  }),
Copy the code

4. Eslint syntax error

In practice, even after webpack is configured correctly, the startup console displays error ‘$’ is not defined no-undef, indicating that the parser still cannot recognize $. The error message basically tells you that this is an ESLint syntax problem. The no-undef rule will issue a warning when accessing an undefined variable in the current source file. If you want to use global variables in a source file, it is recommended that you define these global variables in ESLint so that ESLint does not issue warnings.

5. Eslint $global variable configuration

  globals: {
    $: true,
  },
Copy the code

6. Complete case

The source code

7. Give a gift