337

I've started using webpack2 (to be precise, v2.3.2) and after re-creating my config I keep running into an issue I can't seem to solve I get (sorry in advance for ugly dump):

ERROR in ./src/main.js
Module not found: Error: Can't resolve 'components/DoISuportIt' in '[absolute path to my repo]/src'
resolve 'components/DoISuportIt' in '[absolute path to my repo]/src'
  Parsed request is a module
  using description file: [absolute path to my repo]/package.json (relative path: ./src)
    Field 'browser' doesn't contain a valid alias configuration
    aliased with mapping 'components': '[absolute path to my repo]/src/components' to '[absolute path to my repo]/src/components/DoISuportIt'
      using description file: [absolute path to my repo]/package.json (relative path: ./src)
        Field 'browser' doesn't contain a valid alias configuration
      after using description file: [absolute path to my repo]/package.json (relative path: ./src)
        using description file: [absolute path to my repo]/package.json (relative path: ./src/components/DoISuportIt)
          as directory
            [absolute path to my repo]/src/components/DoISuportIt doesn't exist
          no extension
            Field 'browser' doesn't contain a valid alias configuration
            [absolute path to my repo]/src/components/DoISuportIt doesn't exist
          .js
            Field 'browser' doesn't contain a valid alias configuration
            [absolute path to my repo]/src/components/DoISuportIt.js doesn't exist
          .jsx
            Field 'browser' doesn't contain a valid alias configuration
            [absolute path to my repo]/src/components/DoISuportIt.jsx doesn't exist
[[absolute path to my repo]/src/components/DoISuportIt]
[[absolute path to my repo]/src/components/DoISuportIt]
[[absolute path to my repo]/src/components/DoISuportIt.js]
[[absolute path to my repo]/src/components/DoISuportIt.jsx]

package.json

{
  "version": "1.0.0",
  "main": "./src/main.js",
  "scripts": {
    "build": "webpack --progress --display-error-details"
  },
  "devDependencies": {
    ...
  },
  "dependencies": {
    ...
  }
}

In terms of the browser field it's complaining about, the documentation I've been able to find on this is: package-browser-field-spec. There is also webpack documentation for it, but it seems to have it turned on by default: aliasFields: ["browser"]. I tried adding a browser field to my package.json but that didn't seem to do any good.

webpack.config.js

import path from 'path';
const source = path.resolve(__dirname, 'src');

export default {
  context: __dirname,
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js',
  },
  resolve: {
    alias: {
      components: path.resolve(__dirname, 'src/components'),
    },
    extensions: ['.js', '.jsx'],
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        include: source,
        use: {
          loader: 'babel-loader',
          query: {
            cacheDirectory: true,
          },
        },
      },
      {
        test: /\.css$/,
        include: source,
        use: [
          { loader: 'style-loader' },
          {
            loader: 'css-loader',
            query: {
              importLoader: 1,
              localIdentName: '[path]___[name]__[local]___[hash:base64:5]',
              modules: true,
            },
          },
        ],
      },
    ],
  },
};

src/main.js

import DoISuportIt from 'components/DoISuportIt';

src/components/DoISuportIt/index.jsx

export default function() { ... }

For completeness, .babelrc

{
  "presets": [
    "latest",
    "react"
  ],
  "plugins": [
    "react-css-modules"
  ],
  "env": {
    "production": {
      "compact": true,
      "comments": false,
      "minified": true
    }
  },
  "sourceMaps": true
}

What am I doing wrong/missing?

codejockie
  • 9,020
  • 4
  • 40
  • 46
Matthew Herbst
  • 29,477
  • 23
  • 85
  • 128

43 Answers43

324

Turned out to be an issue with Webpack just not resolving an import - talk about horrible horrible error messages :(

// I Had to change:
import DoISuportIt from 'components/DoISuportIt';

// to (notice the missing `./`)
import DoISuportIt from './components/DoISuportIt';
Matthew Herbst
  • 29,477
  • 23
  • 85
  • 128
  • 3
    Is the issue caused by npm ? Today I upgraded a module using npm, by uninstalling and installing a latest version of module, Now I got this error and the error tells to change the relative location of module, but the list of files is bit high, what caused all these files to change its relative position? – DEEPAN KUMAR Sep 06 '17 at 14:31
  • 5
    This also saved my ass. It's somewhat counter intuitive that in the sass files you can import with 'folder' but in .js files you need to do it like './folder' . Also without --display-error-details there's NO error message what so ever, it just crashes – CoolGoose Dec 10 '17 at 09:34
  • 8
    @Matthew Herbst one of the stupidest error messages:) my ass is saved, thx! – Dmitry Senkovich Feb 13 '18 at 08:40
  • 2
    Similarly, when using Karma-webpack I had to use a ./ where I didn't expect to. ` new webpack.NormalModuleReplacementPlugin(/angulartics$/, './angulartics.mock.ts'),` – Richard Collette Aug 07 '18 at 01:50
  • Is there some configuration for the automatic relative-to-absolute paths conversion while compilation form less ? I have a 3rd-party app (calendar) which on `webpack-dev-server --inline --hot --config examples/webpack.config.js` throws the same and I don't want to monkey-patch. (I also noticed the funny of 4chan-like up-votes in this comments - all of them are equally +1 LOL) – boldnik Aug 28 '18 at 08:29
  • 62
    Still in almost 2022 in webpack 5 the same terrible error messages. No progress from v4 to v5 in thi way? – mikep Dec 03 '21 at 14:15
  • I am facing the same problem, but I still want to use @ as the path.https://stackoverflow.com/questions/70902895/field-browser-doesnt-contain-a-valid-alias-configuration-when-i-changed-the-i @Matthew Herbst – Dolphin Jan 29 '22 at 06:40
  • Cleary there is no right answer. This means that webpack has done a terrible job with error handling and need to make improvements. – RashadRivera Jan 24 '23 at 22:21
75

Just for record, because I had similiar problem, and maybe this answer will help someone: in my case I was using library which was using .js files and I didn't had such extension in webpack resolve extensions. Adding proper extension fixed problem:

module.exports = {
(...)
  resolve: {
    extensions: ['.ts', '.js'],
  }
}
Furman
  • 2,017
  • 3
  • 25
  • 43
38

I'm building a React server-side renderer and found this can also occur when building a separate server config from scratch. If you're seeing this error, try the following:

  1. Make sure your entry value is properly pathed relative to your context value. Mine was missing the preceeding ./ before the entry file name.
  2. Make sure you have your resolve value included. Your imports on anything in node_modules will default to looking in your context folder, otherwise.

Example:

const serverConfig = {
name: 'server',
context: path.join(__dirname, 'src'),
entry: {serverEntry: ['./server-entry.js']},
output: {
    path: path.join(__dirname, 'public'),
    filename: 'server.js',
    publicPath: 'public/',
    libraryTarget: 'commonjs2'
},
module: {
    rules: [/*...*/]
},
resolveLoader: {
    modules: [
        path.join(__dirname, 'node_modules')
    ]
},
resolve: {
    modules: [
        path.join(__dirname, 'node_modules')
    ]
}
};
messerbill
  • 5,499
  • 1
  • 27
  • 38
Artif3x
  • 4,391
  • 1
  • 28
  • 24
24

I encountered this error in a TypeScript project. In my webpack.config.js file I was only resolving TypeScript files i.e.

resolve: {
    extensions: [".ts"],
}

However I noticed that the node_module which was causing the error:

Field 'browser' doesn't contain a valid alias configuration

did not have any ".ts" files (which is understandable as the module has been converted to vanilla JS. Doh!).

So to fix the issue I updated the resolve declaration to:

resolve: {
    extensions: [".ts", ".js"],
}
Ben Smith
  • 19,589
  • 6
  • 65
  • 93
20

I had the same issue, but mine was because of wrong casing in path:

// Wrong - uppercase C in /pathCoordinate/
./path/pathCoordinate/pathCoordinateForm.component

// Correct - lowercase c in /pathcoordinate/
./path/pathcoordinate/pathCoordinateForm.component
baltzar
  • 446
  • 4
  • 8
13

Add this to your package.json:

"browser": {
  "[module-name]": false   
},
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
kimo_ouz
  • 323
  • 4
  • 7
  • i coder should read the documentation first, i always search in stackoverflow but nowadays i prefer to read documentation first. thanks for editing... – kimo_ouz Oct 23 '20 at 12:36
  • I have solved the problem with the main.js, neverthless I have the next error: **Error during loading: Uncaught TypeError: fs.existsSync is not a function in http://localhost:9876/_karma_webpack_/vendor.js line 110252** Do you have any idea about this? – Alberto Bricio Jan 08 '21 at 09:34
  • @kimo_ouz - Absolutely brilliant! Thank you for introducing me to the "browser" field world. Here are some links for other interested people: [insides of the webpack-package.json relationship](https://www.jonathancreamer.com/how-webpack-decides-what-entry-to-load-from-a-package-json/) and [NPM official notes](https://docs.npmjs.com/cli/v7/configuring-npm/package-json#browser) – Marco Faustinelli Mar 25 '21 at 12:32
8

This also occurs when the webpack.config.js is simply missing (dockerignore ‍♂️)

EvgenyKolyakov
  • 3,310
  • 2
  • 21
  • 31
  • 1
    when running `npm run build` i had to modify the build script in `package.json` to reference the correct webpack configuration file `"build": "webpack --mode production --config webpack/webpack.config.prod.js";` – Nwawel A Iroume Apr 22 '22 at 00:22
  • 1
    I also saw this when someone accidentally had `webpackconfig.js` instead of `webpack.config.js`. – Phoenix Jun 07 '23 at 18:54
7

Changed my entry to

entry: path.resolve(__dirname, './src/js/index.js'),

and it worked.

Abraham Jagadeesh
  • 1,757
  • 1
  • 23
  • 21
6

In my case it was a package that was installed as a dependency in package.json with a relative path like this:

"dependencies": {
  ...
  "phoenix_html": "file:../deps/phoenix_html"
},

and imported in js/app.js with import "phoenix_html"

This had worked but after an update of node, npm, etc... it failed with the above error-message.

Changing the import line to import "../../deps/phoenix_html" fixed it.

TNT
  • 3,392
  • 1
  • 24
  • 27
6

My case was rather embarrassing: I added a typescript binding for a JS library without adding the library itself.

So if you do:

npm install --save @types/lucene

Don't forget to do:

npm install --save lucene

Kinda obvious, but I just totally forgot and that cost me quite some time.

Good Night Nerd Pride
  • 8,245
  • 4
  • 49
  • 65
5

In my case, to the very end of the webpack.config.js, where I should exports the config, there was a typo: export(should be exports), which led to failure with loading webpack.config.js at all.

const path = require('path');

const config = {
    mode: 'development',
    entry: "./lib/components/Index.js",
    output: {
        path: path.resolve(__dirname, 'public'),
        filename: 'bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: path.resolve(__dirname, "node_modules")
            }
        ]
    }
}

// pay attention to "export!s!" here
module.exports = config;
luiscla27
  • 4,956
  • 37
  • 49
Leon
  • 811
  • 10
  • 21
5

I had aliases into tsconfig.json:

{
    "compilerOptions": {
        "paths": {
            "@store/*": ["./src/store/*"]
        }
    },
}

So I solved this issue by adding aliases to webpack.config also:

module.exports = {
  //...
  resolve: {
    alias: {
      '@store': path.resolve(__dirname, '../src/store'),
    },
  },
};
zemil
  • 3,235
  • 2
  • 24
  • 33
5

I got same problem and fixed with adding file extension.

// Old:

import RadioInput from './components/RadioInput'

// New:

import RadioInput from './components/RadioInput.vue'

Also, if you still want to use without extensions, you can add this webpack config: (Thanx for @matthew-herbst for the info)

module.exports = {
  //...
  resolve: {
    extensions: ['.js', '.json', '.wasm'], // Add your extensions here.
  },
};
wpuzman
  • 340
  • 1
  • 5
  • 14
  • 2
    You should be able to not need the extension if you pass the custom `resolve.extensions`: https://webpack.js.org/configuration/resolve/#resolveextensions – Matthew Herbst Sep 04 '22 at 13:46
5

I was getting the same error and I didn't want absolute imports. My normal relative import was not working with the same error and "module not found".

I was missing this in my webpack config.

resolve: {
  extensions: ['.tsx', '.ts', '.js'],
}
Ronn Wilder
  • 1,228
  • 9
  • 13
3

For anyone building an ionic app and trying to upload it. Make sure you added at least one platform to the app. Otherwise you will get this error.

olivier
  • 2,585
  • 6
  • 34
  • 61
3

In my experience, this error was as a result of improper naming of aliases in Webpack. In that I had an alias named redux and webpack tried looking for the redux that comes with the redux package in my alias path.

To fix this, I had to rename the alias to something different like Redux.

codejockie
  • 9,020
  • 4
  • 40
  • 46
3

In my case, it was due to a broken symlink when trying to npm link a custom angular library to consuming app. After running npm link @authoring/canvas

"@authoring/canvas": "path/to/ui-authoring-canvas/dist"

It appear everything was OK but the module still couldn't be found:

Error from npm link

When I corrected the import statement to something that the editor could find Link:

import {CirclePackComponent} from '@authoring/canvas/lib/circle-pack/circle-pack.component';

I received this which is mention in the overflow thread:

Field Browser doesn't contain a valid alias configuration

To fix this I had to:

  1. cd /usr/local/lib/node_modules/packageName
  2. cd ..
  3. rm -rf packageName
  4. In the root directory of the library, run:
a) rm -rf dist
b) npm run build
c) cd dist 
d) npm link
  1. In the consuming app, update the package.json with:
"packageName": "file:/path/to/local/node_module/packageName""
  1. In the root directory of the consuming app run npm link packageName
luiscla27
  • 4,956
  • 37
  • 49
Sankofa
  • 600
  • 2
  • 7
  • 19
3

In my case (lolz),

I was importing a local package (that I was developing, and building with rollup) via NPM/Yarn link, into another package I was developing. The imported package was a load of React components, and was configured to have a peerDependency of react and react-dom.

The consuming package was being built with Webpack and obviously wasn't correctly feeding the installed react and react-dom libraries into my local dependency as it was compiling it.

I adjusted my webpack configuration to indicate it should alias those peer dependencies to the correct dependencies in the consuming package:

/* ... */

resolve: {
  extensions: [/* make sure you have them all correct here, as per other answers */],
  alias: {
    react: path.resolve('./node_modules/react'),
    'react-dom': path.resolve('./node_modules/react-dom')
  }
},

/* ... */

Obviously you need to import path in the webpack.config.js file in order to use the methods seen above.

A more detailed explanation can be found in this article

shennan
  • 10,798
  • 5
  • 44
  • 79
2

My case was similar to @witheng's answer.

At some point, I noticed some casing error in some file names in my development environment. For example the file name was

type.ts

and I renamed it to

Type.ts

In my Mac dev environment this didn't register as a change in git so this change didn't go to source control.

In the Linux-based build machine where the filenames are case-sensitive it wasn't able to find the file with different casing.

To avoid issues like this in the future, I ran this command in the repo:

git config core.ignorecase false
Volkan Paksoy
  • 6,727
  • 5
  • 29
  • 40
  • Volkan, how can I get in touch with you? You website has no email on it. Want to ask a question about one of your blog posts, namely https://volkanpaksoy.com/archive/2018/12/19/Monitoring-EC2-Instance-Disk-Space-with-AWS-CloudWatch/ – Robert Benedetto Apr 15 '21 at 06:17
  • 1
    @RobertBenedetto Probably easiest and most efficient way would be asking it here (or another StackExchange site if it's more relevant to your question) and post the link here. Then not only I can take a look but you'd probably get faster and better help from the entire community. – Volkan Paksoy Apr 15 '21 at 07:03
  • True. I'll do that. However, was just going to ask you to update it since the procedure for step 5 seems to have changed, and ask if there is any way to do step 6 using the AWS management site? I'm pretty entry level with AWS, and those two steps are very confusing. – Robert Benedetto Apr 15 '21 at 08:07
  • Asked it here: https://stackoverflow.com/questions/67104686/adding-free-disk-space-metrics-to-aws-cloudwatch – Robert Benedetto Apr 15 '21 at 08:14
  • It's been a while since I published that post and I don't really using EC2 instances at the moment. I wasn't aware of the changes. Hope somebody will be able to weigh in with the latest information. Have you also checked out the links in the resources section? If the resources in that post updated maybe you can get the latest info from them as well. – Volkan Paksoy Apr 15 '21 at 08:21
2

In my case,

I have mistakenly removed a library ("mini-create-react-context") from package.json. I added that back, and did yarn install and build the app and it start working properly. So please take a look at your package.json file once.

Hari Krishnan
  • 191
  • 1
  • 1
  • 8
2

In my case I had accidentally imported this package while trying to use process.env:

import * as process from 'process';

Removing it fixed the problem.

6infinity8
  • 298
  • 4
  • 10
1

For everyone with Ionic: Updating to the latest @ionic/app-scripts version gave a better error message.

npm install @ionic/app-scripts@latest --save-dev

It was a wrong path for styleUrls in a component to a non-existing file. Strangely it gave no error in development.

alex351
  • 1,826
  • 1
  • 21
  • 32
1

In my situation, I did not have an export at the bottom of my webpack.config.js file. Simply adding

export default Config;

solved it.

dxhans5
  • 127
  • 1
  • 12
1

In my case, it is due to a case-sensitivity typo in import path. For example,

Should be:

import Dashboard from './Dashboard/dashboard';

Instead of:

import Dashboard from './Dashboard/Dashboard';
wltheng
  • 750
  • 1
  • 11
  • 26
1

In my case I was using invalid templateUrl.By correcting it problem solved.

@Component({
        selector: 'app-edit-feather-object',
        templateUrl: ''
    })
AmirHossein Rezaei
  • 1,086
  • 1
  • 16
  • 20
1

I am using single-spa, and encountered this issue with the error

Module not found: Error: Can't resolve '/builds/**/**/src\main.single-spa.ts' in /builds/**/**'

I eventually figured out that in angular.json build options "main" was set to src\\main.single-spa.ts. Changing it to src/main.single-spa.ts fixed it.

enter image description here

Jadamae77
  • 828
  • 7
  • 13
1

In my case, I imported library files like:

import { MyFile } from "my-library/public-api";

After I removed the public-api from the import everything worked fine:

import { MyFile } from "my-library";

MyFile is exported in the public-api file in the library.

FAndrew
  • 248
  • 4
  • 22
1

I was getting this error when running a GitHub action. The issue was because I'd listed the package as a peer dependency instead of a dependency.

Since I'm using Rollup, the solution was to install the package both as a peer dependency and a dev dependency, and use rollup-plugin-peer-deps-external to remove the dev dependency from the final build.

Sauce
  • 652
  • 6
  • 12
1

For me the issue was, I was importing

.ts files into .js files

changing them to ts as well solved the issue.

Ankur Marwaha
  • 1,613
  • 2
  • 15
  • 30
1

In my case, I had a mixture of enum and interface in the index.d.ts file.
I extracted enums into another file and the issue resolved.

Mostafa Armandi
  • 879
  • 1
  • 11
  • 24
1

In my case, entry field was missing under module.exports in webpack.config.js, causing this issue.

Yogesh Kumar Gupta
  • 1,009
  • 1
  • 10
  • 10
1

For anyone using Webpack's Module Federation plugin:
I had a typo in the value of one of the fileds in the 'exposes' entry of the plugin.
Check your spelling:

exposes: {
            './ShopApp': './src/bootstrap' // check this value
        }
Nati Kamusher
  • 533
  • 5
  • 9
1

In my case(:p), I had a .d.ts file originally meant to contain definitions, but i defined an exported enum inside it. I was not resolving this file in webpack, since it only contained definition.

Moving enum to a separate .ts file resolved the issue.

Yogesh Kumar Gupta
  • 1,009
  • 1
  • 10
  • 10
1

In my case, this error was a result of no entry point being found by webpack. If an entry point is not defined explicitly in your webpack config, the entry point is by default ./src/index.js If such a path doesn't exist you will get this error.

To change the path to the entry point, use the entry setting in your config file (https://webpack.js.org/configuration/entry-context/#root).

Ben H
  • 21
  • 4
1

In my case this fixed it. I changed this:

import {setupModel} from './setup-model.js';

To this:

import {setupModel} from './setup-model';
Arshaan
  • 61
  • 6
0

I'm using "@google-cloud/translate": "^5.1.4" and was truggling with this issue, until I tried this:

I opened google-gax\build\src\operationsClient.js file and changed

const configData = require('./operations_client_config');

to

const configData = require('./operations_client_config.json');

which solved the error

ERROR in ./node_modules/google-gax/build/src/operationsClient.js Module not found: Error: Can't resolve './operations_client_config' in 'C:\..\Projects\qaymni\node_modules\google-gax\build\src' resolve './operations_client_config' ......

I hope it helps someone

Abeer Sul
  • 944
  • 9
  • 22
0

Had the same issue with angular was importing

import { Injectable } from "@angular/core/core";

changed it to

import { Injectable } from "@angular/core";
Avinash
  • 305
  • 6
  • 14
0

In my case, I was getting this error: (I am using webpack 5 with React v18 and React Router v6)

ERROR in ./src/components/App/App.jsx 5:0-42
Module not found: Error: Can't resolve '../../Pages/Profile' in 'C:\Users\nicho\Desktop\projects\webpack-starter-with-react\src\components\App'  
resolve '../../Pages/Profile' in 'C:\Users\nicho\Desktop\projects\webpack-starter-with-react\src\components\App'
  using description file: C:\Users\nicho\Desktop\projects\webpack-starter-with-react\package.json (relative path: ./src/components/App)
    Field 'browser' doesn't contain a valid alias configuration
    using description file: C:\Users\nicho\Desktop\projects\webpack-starter-with-react\package.json (relative path: ./src/Pages/Profile)
      no extension
        Field 'browser' doesn't contain a valid alias configuration
        C:\Users\nicho\Desktop\projects\webpack-starter-with-react\src\Pages\Profile doesn't exist
      .js
        Field 'browser' doesn't contain a valid alias configuration
        C:\Users\nicho\Desktop\projects\webpack-starter-with-react\src\Pages\Profile.js doesn't exist
      .json
        Field 'browser' doesn't contain a valid alias configuration
        C:\Users\nicho\Desktop\projects\webpack-starter-with-react\src\Pages\Profile.json doesn't exist
      .wasm
        Field 'browser' doesn't contain a valid alias configuration
        C:\Users\nicho\Desktop\projects\webpack-starter-with-react\src\Pages\Profile.wasm doesn't exist
      as directory
        C:\Users\nicho\Desktop\projects\webpack-starter-with-react\src\Pages\Profile doesn't exist
 @ ./src/index.js 3:0-43 5:46-49

webpack 5.72.1 compiled with 3 errors in 1872 ms

Adding the file extension to the module import fixed this for me:

from this:

import Home from '../../Pages/Home'

to this:

import Home from '../../Pages/Home.jsx'
0

On Windows PowerShell, the following command raises this error:

npx webpack .\src\js\main.js --output-filename output.js

The correct command is:

npx webpack ./src/js/main.js --output-filename output.js

Notice that when using npx, even on Windows, we have to use the Linux path separator (/).

Gaurang Tandon
  • 6,504
  • 11
  • 47
  • 84
0

In my case :)

$ rm -rf tsconfig.tsbuildinfo
$ npm run build
benaja
  • 137
  • 11
0

Maybe you run webpack serve and not specify the location of the configuration file. For example: Your package.json file

"script": {
  "dev": "webpack serve"
}

But your webpack configs are in a config directory.So you should change the script:

"script": {
  "dev": "webpack serve --config ./config/webpack.config.js"
}
Ha0ran
  • 585
  • 5
  • 13
0

A possible reason, would be, if you have nullified a certain dependency in webpack.config.js:

resolve: {
    fallback: {
        fs: false,
        path: false,
    },
},

You also need to add to package.json:

"browser": {
    "fs": false,
    "path": false,
}, 
Weilory
  • 2,621
  • 19
  • 35
0

I had quite funny solution with the same error, during development and I have deleted index.html from src folder. But it has remained in dist folder as I had no webpack clean on dev serv launch. Basically without index html dev serv will not work and will return you error posted above. Soultion is to either add index.html or add different devserf default html file

KSDev
  • 11
  • 1
  • 4