📜 ⬆️ ⬇️

Webpack ProvidePlugin: how not to write a sheet import / require at the beginning of the javascript module

If you are developing in modern javascript, then almost any of your modules contains a sheet of such strings:

import React from 'react' import $ from 'jquery' ... 

As it turned out, most of these lines can not be written, entrusting their generation to automatics. And it helps in this newfangled webpack , which, as it turns out, is full of pleasant surprises. In addition to the well-known require and import for any files already described on the hot module replacement, the webpack can analyze your source code and automatically include the necessary modules based on the used literals. Under the cut - a brief description of how this magic works.

For the analysis of your source code and the automatic creation of import directives, there is a special ProviderPlugin plugin that is built into the webpack and does not require installation. For the magic to work, you need to specify a plugin in the wbpack configuration file and provide it with a list of identifiers and modules. As you know, webpack uses the esprima parser, and therefore has a very accurate idea of ​​the structure of your code. Upon encountering the specified identifier in the source, the webpack will generate the load code for the specified module in the same way as it does for import or require . Fragment of the configuration file:

 module.exports = { plugins: [ new webpack.ProvidePlugin({ 'React': 'react', ... 

When using the plugin with the configuration from the example, the webpack will look for the use of the React ID . He will ignore this line:
')
 const foo = "React"; 

and even this:

 bar.React = true; 

But having met this one, he will immediately understand that ReactJS is used in this module and provide the bundle fragment with the corresponding module loading code:

 React.createClass(…) 

And of course, no one restricts you only ReactJS . Use this method for popular libraries and often used modules of your own project to make the code more concise and easier:

 new webpack.ProvidePlugin({ '$': 'jquery', '_': 'lodash', 'ReactDOM': 'react-dom', 'cssModule': 'react-css-modules', 'Promise': 'bluebird' }) 

PS


If you, like me, want to use ES6 import instead of the old require , this is done by specifying babel as a loader for webpack . And do not forget about .babelrc and presets - in the latest version of babel, developers prepared a surprise for beginners, without specifying the presets, babel now does nothing:

 module.exports = { module: { loaders: [{ test: /\.js$/, loaders: ['babel'], ... 

Source: https://habr.com/ru/post/274385/


All Articles