Webpack: configure path mapping

505 Views Asked by At

This is probably a trivial problem, but I am new to webpack. I have a project where the include paths seem to be messed up. The project structure looks like this (simplified):

app/
├─ webpack.config.js
├─ dist/
├─ src/
│  ├─ main.js
│  ├─ modules/
│  │  ├─ button/
│  │  │  ├─ button.js
│  │  ├─ link/
│  │  │  ├─ link.js
      ... many more

Note that each module has its own subfolder. The main.js looks like this:

import './modules/button';
import './modules/link';
...

Modules can import other modules:

// app/src/modules/button/button.js
import { mediaLink } from '../link';

I have a basic webpack.config.js set up that looks like this:

const path = require('path');

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'app.js',
  },
};

For some reason, all imports don't consider the module's subfolders. When i run webpack, I get a lot of Module not found: Error: Can't resolve ... errors. The error output looks like this:

ERROR in ./src/main.js
Module not found: Error: Can't resolve './modules/button' in '/path/to/project/app/src'
 @ ./src/main.js 8:0-27

Can I configure webpack to use some kind of mapping when it imports a module?

1

There are 1 best solutions below

2
On

If the tree is

├─ src/
│  ├─ main.js
│  ├─ modules/
│  │  ├─ button/
│  │  │  ├─ button.js

then src/main.js will need to

import './modules/button/button';

or, if button.js was named index.js (resolve.mainFiles),

import './modules/button';

would work.

Yes, you can set up aliases/mappings, but that's probably not worth it (especially when you consider your IDE/editor/... would also need to know about the mappings).

Just try renaming those button/button.jses and link/link.jses to button/index.js, link/index.js etc. first.