44

Lets say theres a package in node_modules called foo and I want to import a module within a library such as foo/module via webpack & babel...

import Foo from 'foo'; works

import SomeOtherModule from 'foo/module'; fails with the following:

Module not found: Error: Cannot resolve module 'foo/module' in /Users/x/Desktop/someproject/js

Which makes make it seem like webpack is looking for the file in the wrong place instead of node_modules

My webpack.config looks like this:

var webpack = require('webpack'); var path = require('path'); module.exports = { entry: ['babel-polyfill','./js/script.js'], output: { path: __dirname, filename: './build/script.js' }, module: { loaders: [ { test: /\.js$/, loader: 'babel', query: { cacheDirectory: true, presets: ['es2015'] } } ], }, plugins: [ new webpack.NoErrorsPlugin() ], stats: { colors: true }, devtool: 'source-map' }; 
1
  • 1
    Show file and folder structure for foo module, please Commented Jan 16, 2016 at 18:44

2 Answers 2

34

It should work with import 'foo/module';. It will resolve file ./node_modules/foo/module.js or ./node_modules/foo/module/index.js and not something like ./node_modules/foo/node_modules/module/index.js if it expected (in that case you better to install module via npm).

Sign up to request clarification or add additional context in comments.

6 Comments

structure for the module is ./node_modules/foo/module/index.js which doesnt resolve
I checked in test project and it worked, when I rename ./node_modules/foo/module/index.js to ./node_modules/foo/module/index1.js , run webpack, it says "Cannot resolve module 'foo/module' in /home/user/www/so-2/js". So, maybe you have typo in filename?
oh you're right, the module foo has a folder src so import from foo/src/module worked thanks
@DmitryYaremenko Is there a way to import via import 'foo/module'; a module.jsfile if the file itself has the following path: foo/src/module.js? I don't want the src/ subdirectory to be in the path when importing...
@tonix You can try to add alias: webpack.js.org/configuration/resolve , something like foo: "foo/src"
|
1

You can define a custom path using the module attribute in your package.json. Example:

{ ... "module": "dist/mylib.min.js", ... } 

See What is the "module" package.json field for?

1 Comment

"... Node.js ignored (and still ignores) the top-level "module" field." (source:nodejs.org/api/esm.html#esm_dual_commonjs_es_module_packages) - they very much seem to not want to support this additional field inside package.json

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.