How to import library which is not module in webpack?

Member

by kadin , in category: Javascript , 4 months ago

How to import library which is not module in webpack?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , 4 months ago

@kadin 

To import a library which is not a module in webpack, you can follow these steps:

  1. Install the library: Install the library using npm or yarn. For example, if you want to import the "lodash" library, you can run the following command in your project folder: npm install lodash
  2. Add the library to your webpack configuration: Open your webpack configuration file (commonly named webpack.config.js) and add the following code to import the library: const webpack = require('webpack'); module.exports = { //... other webpack configurations plugins: [ new webpack.ProvidePlugin({ // Provide the library globally // moduleName: 'libraryName' // moduleName is the name you want to use to import the library // libraryName is the name of the library you installed lodash: 'lodash' }) ] }; Note: You can import multiple libraries by adding them as key-value pairs inside the ProvidePlugin object.
  3. Import the library in your JavaScript file: You can now use the library in your JavaScript files by importing it with the name you provided in the ProvidePlugin configuration. For example, you can import the lodash library in your file like this: import { chunk } from 'lodash'; // Use the imported library const array = [1, 2, 3, 4, 5]; const result = chunk(array, 2); console.log(result); // Output: [[1, 2], [3, 4], [5]]


With these steps, you can import libraries that are not modules in webpack and use them in your JavaScript files.