Skip to content Skip to sidebar Skip to footer

Import From Node_modules Not Recognized In Es6 Modules In Browser

I'm trying to use lodash in my web application. I have installed lodash using npm in my local project. I plan on using the ES6 modules in my code. Here is my main.js file: import

Solution 1:

If you don't wish to use any bundling tools, you will need to provide a path to the lodash folder within node_modules, relative to the JavaScript file that you have the import statement in.

If you do not wish to use a bundler, it would also be worthwhile importing from the specific file, the function you need. For example:

import _each from'../node_modules/lodash/each'

Solution 2:

As of 2021, please consider the following statement by Márton Salomváry (Jan 2018):

Unfortunately even most libraries authored or published in ES6 module format will not work because they target transpilers and rely on the Node.js ecosystem. Why is that a problem? Using bare module paths like import _ from 'lodash' is currently invalid, browsers don’t know what to do with them.

And also the statement by Jake Archibald (May 2017):

"Bare" import specifiers aren't currently supported.

Valid module specifiers must match one of the following:

  1. A full non-relative URL.
  2. Starts with /.
  3. Starts with ./.
  4. Starts with ../.

And javascript.info:

In the browser, import must get either a relative or absolute URL. Modules without any path are called “bare” modules. Such modules are not allowed in import.

Certain environments, like Node.js or bundle tools allow bare modules, without any path, as they have their own ways for finding modules and hooks to fine-tune them. But browsers do not support bare modules yet.

Bundlers facilitate the use of "Bare Imports" which is not supported by the browser yet. Unless you bundle your code, I recommend using the solution proposed by @Asler. Besides, a lot of work is currently being done to study the implementation of "Bare Imports" in the browser, please follow this link if you want to monitor the overall progress.

Solution 3:

Try module lodash-es

import each from'../node_modules/lodash-es/each.js'

Solution 4:

Eventually you can't use JS modules on browser like that. These modules are for webpack or other bundler.

Solution 5:

If you are trying to import css file, make sure to mention .css in import statement.

Post a Comment for "Import From Node_modules Not Recognized In Es6 Modules In Browser"