1

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
0

1 Answer 1

1

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`);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.