brentonstrine
brentonstrine

Reputation: 22742

Why is webpack unable to find react when I'm using a custom entry point?

I set up a custom entry point in Webpack but am getting an error on this line of my React code:

import React from 'react';

Webpack is able to build it, but itsnt intercepting that path because Chrome gives me this console error:

Uncaught TypeError: Failed to resolve module specifier "react". Relative references must start with either "/", "./", or "../"

However, when I change the path as suggested to:

import React from './react';

Then webpack is unable to build and gives this error:

ERROR in ./path/to/my/file.js Module not found: Error: Can't resolve './react' in '/Users/me/Documents/GitHub/myProject/path/to/my @ ./path/to/my/file.js 3:0-28

And furthermore I get this Chrome console error:

GET http://localhost:9000/path/to/my/file/react net::ERR_ABORTED 404 (Not Found)

So webpack is looking for react in path/to/my/ instead of in node_modules as it should.

My webpack.config.js looks like this:

//snip
module.exports = {
    entry: './path/to/my/file.js',
    output: {
        path:  path.join(__dirname, '/build'),
        publicPath: '/',
        filename: 'bundle.js'
    },
    devServer: {
        contentBase: path.join(__dirname, '/'),
        port: 9000
    },
//snip
}

and package.json

{
  //snip
  "main": "path/to/my/file.js",
  //snip
}

Upvotes: 2

Views: 623

Answers (1)

brentonstrine
brentonstrine

Reputation: 22742

This problem is caused by the <script> tag in the HTML file pointing to the actual location of the source script, rather than pointing to the compiled output file that webpack creates.

This is wrong:

<script src="/path/to/my/file.js"></script>

^ That is pointing to the raw source code in its actual location in the repository. It isn't handled by webpack and isn't compiled by babel, it's just a plain javascript file handled by the browser, which explains the browser errors.

This is correct:

<script src="bundle.js"></script>

^ that is pointing to the compiled output that webpack generates based on the configuration. In the dev server, there is not an actual file called bundle.js, the file lives in memory, and the path to that file is just the dev server, e.g. something like http://localhost:8000.

The reason the name is bundle.js is because that's what it happens to be set to in webpack.config.js module output filename. If it's set to something else, it will be that.

output: {
  path:  path.join(__dirname, '/build'),
  publicPath: '/',
  filename: 'bundle.js'
},

Upvotes: 1

Related Questions