SoFunction
Updated on 2025-04-03

Detailed explanation of the ways and precautions for webpack to introduce third-party libraries

Generally speaking, we don’t have to worry about the third-party library we are using, which cannot be found in the npm management repository.

If you need a certain library, such as: jquery, you can run it directlynpm install jqueryScript commands to install the dependencies required for this project;

Then, in the module file using jquery,import $ from 'jquery'orvar $ = require('jquery')Come in.

This is commonly used inWebpack-built projectsHow to introduce third-party libraries.

Note: For a better demonstration of the sample code, the example isnodemonThis article is based on operation.

However, in different scenarios, there are different requirements for projects built by webpack:

The volume of the project is small enough (cdn)

If it is the processing method of webapck, please refer towebpack - achieve minimal build outputThis article.

Use non-webapck processing methods, such as: CDN.

The operation is also very simple, if usedhtml-webpack-pluginDirectly in the template filetemplate/Introduce a third-party library (such as jquery) on a certain cdn (such as boot CDN), and the reference code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>third party</title>
</head>
<body>
  <script src="/jquery/3.3.1/"></script>
</body>
</html>

Then, just use jquery in it, the reference code is as follows:

require('./');
 = function() {
  $().append('<h1>hello webpack</h1>')  
}

Finally, runnpm run test, after the build is finished, you will see it in the browserhello webpackThe words, the background is a red page effect.

Use third-party libraries in a global environment (provide-plugin or imports-loader)

To avoid using a third-party library every time, you need to use itimportorrequire()References to them, you can define them as global variables.

And webpack'sProvidePluginBuilt-in plug-ins can solve this problem. For details, please refer toProvidePluginIntroduction to this article.

Avoid jquery conflicts caused by cdn references, use lodash here.

First, installlodashDependency, command as follows:

yarn add lodash --dev

Then, add the following code:

new ({
    _: 'lodash'
}),

Secondly, inAdd the following code to:

...
var arr = [1, 2, 3, 4, 5 ,6];
// provide-plugin
$().append('<h1>' + _.concat(arr, '~') + '</h1');
...

Finally, runnpm run testAfter the script command is built, you can add it to the browser's page.1,2,3,4,5,6,~。

If, you want to specifylodashA tool function can be used globally, such as: _.concat,

First, modify it like below, the code is as follows:

...
new ({
    // _: 'lodash',
    _concat: ['lodash', 'concat']
}),
...

Then, modify the code as follows:

...
var arr = [1, 2, 3, 4, 5 ,6];
// provide-plugin
// $().append('<h1>' + _.concat(arr, '~') + '</h1');
$().append('<h1>' + _concat(arr, '~') + '</h1');
...

If you don't like using plugins, you can also consider using itimport-loader, it can achieve the same purpose as well.

To avoid unnecessary interference, you can useunderscoreCome to demonstrate.

First, installimports-loaderDependency, command as follows:

yarn add imports-loader --dev

Then, install the underscore dependency, and the command is as follows:

yarn add underscore

Secondly, add the following code in:

...
module: {
    rules: [
        {
            test: ('underscore'),
            use: 'imports-loader?_=underscore'
        },
        ...
    ]
},
...

Note: both underscore and lodash are developed using the singleton pattern. The names of the instantiated constructors are all _. In order to distinguish, you need to change one of them. Imports-loader is a bit difficult to alias this tag, while provide-plugin does not have this problem. You can set a personalized alias.

Modify, the code is as follows:

new ({
    // _: 'lodash',
    // _concat: ['lodash', 'concat'],
    __: 'lodash'
}),

Can belodashDefined as__andunderscoreof_Make a distinction.

Then, modify the code as follows:

...
// provide-plugin
// $().append('<h1>' + _.concat(arr, '~') + '</h1');
// $().append('<h1>' + _concat(arr, '~') + '</h1');
$().append('<h1>' + __.concat(arr, '~') + '</h1');
...

Finally, save all files and you can see similar results in the browser (after saving, nodemon starts the browser itself).

cdn and externals

Have encountered some beforeexternalsThe question, why do you need to be said in detail, is because many people don’t understand what it is used for.

Scene reappearance:

Previously, a project was usedjquery, Due to the classical nature of this library, it is frequently referenced in various modules of the application. The usage is as follows:

import $ from 'jquery'

or

var $ = require('jquery')

The result is that after the build is completed, the file is relatively large. Then consider using cdn, as described above. This requires deleting the import or require references, and also deleting the installed jquery dependencies. However, due to the chaotic project structure and many modules, in order to avoid the problem of less or missed modifications, it will cause application errors. What should I do?

Some people say that if you do not delete jquery dependencies, the purpose of using cdn is meaningless. Using external can solve this problem.

You can add the following code to the file:

...
var $ = require('jquery')
...

Then, save the file and find the following error when the build output prompts:

ERROR in ./
Module not found: Error: Can't resolve 'jquery' in 'E:\workspace\me\webpack-play\demo\example-1'
 @ ./ 3:0-23
 @ ./
 @ multi (webpack)-dev-server/client?http://localhost:8080 ./

The jquery in the module cannot be parsed.

Then, inAdd the following code to:

externals: {

  jquery: 'jQuery',
  jquery: '$'
},

jquery represents jquery in require('jquery'), while jQuery and $ represent instantiated identifiers provided by the jquery library itself. The cdnization of other libraries, and the modification is similar to jquery.

However, if you decide to use cdn at the beginning of the project, don't use jquery module.var $ = require('jquery') orimport $ from 'jquery';, although this will not report an error, if for some considerations, jquery dependencies may be introduced in the later stage, then it must be usedvar $ = require('jquery')orimport $ from 'jquery';

Reference source code

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.