Richard Fernandez
Richard Fernandez

Reputation: 599

ES6 Webpack Relative imports - Module not found: Error: Cannot resolve module

I'm trying to find some information about Webpack and relative imports when working with ES6 and Babel.

I have an import line in a simple entry point in my app:

// app.es6
import * as sayHello from 'sayHello';
console.log(sayHello());

sayHello.es6 is the same directory as app.es6. (The contents of sayHello.es6 is not significant).

When I run the Webpack compiler via the command line:

$ webpack

I get the following error:

ERROR in ./app/app.es6
Module not found: Error: Cannot resolve module 'sayHello' in /Users/username/Code/projectname/app

This is solved by setting the path to relative:

// app.es6 - note the ./ in the import
import * as sayHello from './sayHello';
console.log(sayHello());

This is a bit of a pain because it's different to the example es6 code on Babel website under the Modules section.

Here is my Webpack config:

var path = require('path');
var webpack = require('webpack');

module.exports = {
  entry: [
    'babel-polyfill',
    './app/app.es6'
  ],
  output: {
      publicPath: '/',
      filename: './dist/app.js'
  },
  debug: true,
  devtool: 'source-map',
  module: {
    loaders: [
      {
        test: /\.js|\.es6$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        query:
        {
          presets:['es2015']
        }
      }
    ]
  },
  resolve: {
    extensions: ['', '.js', '.es6'],
  },
};

Question: Does any one know why there is this difference? Or where the relevant information regarding ES6 module imports is in the Webpack documentation?

Upvotes: 0

Views: 11883

Answers (1)

Carlos Sultana
Carlos Sultana

Reputation: 709

This is by design, without prefixing it indicates the module should be loaded from node_modules directory. You can set up an alias in your webpack config which would remove the need for relative module imports

resolve: {
  alias: { 
    sayHello: '/absolute/path/to/sayHello'
  },
  extensions: ['', '.js', '.es6']
}

Then Webpack would fill in the gaps in your import statements and allow you to omit the relative path and import * as sayHello from 'sayHello'; would work throughout your project

Upvotes: 3

Related Questions