BlueEye
BlueEye

Reputation: 13

Webpack require npm module dynamiclly by variable

I can't find a way to require NPM module dynamically by variable.

Here is a sample code what I'm trying to do, Everything works great expect import NPM module dynamically.

const firstModule = 'my-npm-module';
const secondModule = './MyReactComponent';

// NPM Module
import(firstModule).then(...); // Doesn't work
import('my-npm-module').then(...); // Works

// Local React Component
import(secondModule).then(...); // Works
import('./MyReactComponent').then(...); // Works

Upvotes: 1

Views: 204

Answers (1)

CodingIntrigue
CodingIntrigue

Reputation: 78535

From the Webpack docs on dynamic import:

Fully dynamic statements, such as import(foo), will fail because webpack requires at least some file location information. This is because foo could potentially be any path to any file in your system or project. The import() must contain at least some information about where the module is located, so bundling can be limited to a specific directory or set of files.

Your best option would probably be to either not use dynamic loading for anything in node_modules, or add the explicit path to the module, e.g.

import(`./node_modules/${firstModule}/index.js`);

Upvotes: 1

Related Questions