Webpack Error - Cannot Resolve File or Directory - javascript

I am getting this error when I npm start my webpack-dev-server:
ERROR in multi main
Module not found: Error: Cannot resolve 'file' or 'directory' /var/www/html/151208-DressingAphrodite/app in /var/www/html/151208-DressingAphrodite
# multi main
Here is my webpack.config.js:
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require ('html-webpack-plugin');
const PATHS = {
app: path.join (__dirname, 'app'),
build : path.join (__dirname, 'build')
};
module.exports = {
entry : [
'babel-polyfill',
'webpack-dev-server/client?http://localhost:8080',
PATHS.app
],
output : {
publicPath : '/',
filename : 'dressingaphrodite.js',
hash : true
},
debug : true,
devServer : {
contentBase : './app'
},
devtool : 'source-map',
module : {
loaders : [
{
test : /\.jsx?$/,
include : PATHS.app,
loader : 'babel-loader',
query : {
presets : ["es2015"]
}
},
{
test: /\.css$/,
include: PATHS.app,
loader: 'style!css'
}
]
},
plugins : [
new HtmlWebpackPlugin ({
title : 'Dressing Aphrodite',
filename : 'da.html'
})
]
};

ok if any one face this problem, you can solve it in 2 methods:
Method 1:
1- add a file called package.json inside your entry folder (in your case put it inside the folder "{project_dir}/app/package.json")
2- inside this file write any json object for example:
{
"name": "webpack why you do diss :("
}
Method 2:
Change your entry files to be at least 2 level away from your project home directory, for example: "{project_dir}/src/app"
Explanation: for each entry file webpack will try to find a file called package.json to use it for webpack configuration incase this entry file is a module, when you put your entry file only 1 level away from your project home dir webpack will use your project packge.json as configuration file for your entry file and it will fail because of miss configuration.

You should check the browser console. It provides more detailed informations.
In my case:
Uncaught Error: Cannot find module "./src/index"
at webpackMissingModule (webpack:///multi_main?:4)
at eval (webpack:///multi_main?:4)
at Object.<anonymous> (bundle.js:586)
at __webpack_require__ (bundle.js:556)
at bundle.js:579
at bundle.js:582
So here is the error a missing (or misspelled) java script file.

The same problem I met. I found an answer in github Error : ERROR in Entry module not found: Error: Cannot resolve 'file' or 'directory'#981. But sadly, in webpack 1.15.12, the --allow-incompatible-update has been remove. Also, I found when set the entry type is array, such as entry: [entry.js], webpack will run, but throw another error:(
I wish it can help you, hopefully.

Related

Webpack Cannot load pdf file: Module parse failed You may need an appropriate loader to handle this file type

I am new to webpack. Recently, I wanted to find a way to view pdfs in one of my projects. I have found out a library called "react-pdf" (https://www.npmjs.com/package/react-pdf) and decided to experiment with it. When using it in a test react project (npx create-react-app), everything worked fine, but when I to introduced it to the real project, using Nextjs, things went wrong.
import placeholder from "../src/placeholder.pdf""
Every time the server reloads I get this error:
*
error - ./assets/pdf/placeholder.pdf
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)*
This is the webpack config:
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.pdf$/i,
type: 'asset/resource',
generator: {
filename: `[name][ext]`
}
}
],
},
mode: 'development'
};
What am I doing wrong?
next.config.js
module.exports = {
webpack: (config, options) =>
{
config.module.rules.push({
test: /\.pdf$/i,
type: 'asset/source'
})
return config
},
}

Webpack alias pointing to a parent directory which dosn't have webpack configured

I have a project which doesn't include webpack in the root direct, it's installed in my website folder within root directory.
project
-> src
-> App.js
-> Hello.js
-> index.js
-> website
-> webpack.config.js
-> index.js
-> package.json
and in my webpack.config.js file I added a alias entry to point to my components folder:
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
},
resolve: {
alias: {
'#my-app/components': path.resolve(__dirname, '../src/'),
}
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
}
]
},
}
The problem is: When I try to import my component like this import { Hello } from '#my-app/components'; and I try to npm run build, I get this error message:
ERROR in ../src/Hello.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /Users/.../my-new-proj/src/Hello.js: Unexpected token (4:2)
I'm not sure if this problem is caused just because I'm pointing my components alias in a parent directory which doesn't have its own webpack config or it's something else.
I pushed my code to github so you can see the complete folder structure: https://github.com/osnysantos/my-new-project
Your problem has nothing to do with webpack alias. If you follow the the emitted error, you will see that babel-loader does not recognize the JSX. I see you have added react-presets to your babelrc file, however those seem to be overwritten by your webpack config. Either remove the preset array from the webpack config, or add react preset to them.

Entry module not found: Error: Can't resolve './src/index.js'

I was installing a react startup app and added Webpack, but it says Can't resolve './src/index.js'.
Browser Shows
My Files Path and Package.json Contents
Webpack.config.js Contents
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');
module.exports = {
context: path.join(__dirname, "public"),
devtool: debug ? "inline-sourcemap" : false,
entry: "./src/index.js",
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2016', 'stage-0'],
plugins: ['react-html-attrs', 'transform-decorators-legacy', 'transform-class-properties'],
}
}
]
},
output: {
path: __dirname + "/public/",
filename: "build.js"
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
};
Your base URL is path.join(__dirname, "public"), and your entry is ./src/index.js. Webpack tries to find ./src/index.js in public dir; obviously it does not exist. You should modify entry to ../src/index.js.
The other way I find out to fix this problem is to use path.resolve().
const path = require('path');
module.exports = {
mode: "production",
entry: path.resolve(__dirname, 'src') + 'path/to/your/file.js',
output: {
/*Webpack producing results*/
path: path.resolve(__dirname, "../src/dist"),
filename: "app-bundle.js"
}
}
This will make sure, webpack is looking for entry point in src directory.
By the way it's the default entry point. You can also change this entry point to your suitable location. Just replace the src directory with the other directory you want to use.
My webpack.config.js was named Webpack.config.js and the new cli was looking for something case-sensitive.
Webpack does not look for .js files by default. You can configure resolve.extensions to look for .ts. Don't forget to add the default values as well, otherwise most modules will break because they rely on the fact that the .js extension is automatically used.
resolve: {
extensions: ['.js', '.json']
}
The entry path is relative to the context. It's looking for a file in public/src/ when you want it to look for a path in just /src. Looking at the rest of your webpack.config.js it doesn't seem like you need the context line at all.
https://webpack.js.org/configuration/entry-context/
I had the same problem and found that it was caused by having installed create-react-app globally in the past using npm install -g create-react-app.
As create-react-app should now not be installed globally, I needed to uninstall it first using npm uninstall -g create-react-app and then install it in my project directory with npx create-react-app *my-app-name*.
My solution was to put App.js file on a components folder inside the src folder and keep the inde.js just inside the src one
I had same problem. And solutions was really 'at the top' I forgot to add module.exports inside my webpack.prod.js.
So instead of
merge(common, {
...
});
use
module.exports = merge(common, {
...
});

WebPack configuration- what is the proper code and what does it mean

I'm learning React and want to understand how web pack is configured for a project.
It would be great if someone can tell me what the following lines of code are doing.
const fs = require('fs')
const path = require('path')
const webpack = require('webpack')
function isDirectory(dir) {
return fs.lstatSync(dir).isDirectory()
}
const SubjectsDir = path.join(__dirname, 'subjects')
const SubjectDirs = fs.readdirSync(SubjectsDir).filter(function (dir) {
return isDirectory(path.join(SubjectsDir, dir))
})
module.exports = {
devtool: 'source-map',
entry: SubjectDirs.reduce(function (entries, dir) {
if (fs.existsSync(path.join(SubjectsDir, dir, 'exercise.js')))
entries[dir + '-exercise'] = path.join(SubjectsDir, dir, 'exercise.js')
if (fs.existsSync(path.join(SubjectsDir, dir, 'solution.js')))
entries[dir + '-solution'] = path.join(SubjectsDir, dir, 'solution.js')
if (fs.existsSync(path.join(SubjectsDir, dir, 'lecture.js')))
entries[dir + '-lecture'] = path.join(SubjectsDir, dir, 'lecture.js')
return entries
}, {
shared: [ 'react', 'react-dom' ]
}),
output: {
path: '__build__',
filename: '[name].js',
chunkFilename: '[id].chunk.js',
publicPath: '__build__'
},
resolve: {
extensions: [ '', '.js', '.css' ]
},
module: {
loaders: [
{ test: /\.css$/, loader: 'style!css' },
{ test: /\.js$/, exclude: /node_modules|mocha-browser\.js/, loader: 'babel' },
{ test: /\.woff(2)?$/, loader: 'url?limit=10000&mimetype=application/font-woff' },
{ test: /\.ttf$/, loader: 'file' },
{ test: /\.eot$/, loader: 'file' },
{ test: /\.svg$/, loader: 'file' },
{ test: require.resolve('jquery'), loader: 'expose?jQuery' }
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({ name: 'shared' })
],
devServer: {
quiet: false,
noInfo: false,
historyApiFallback: {
rewrites: [
{ from: /ReduxDataFlow\/exercise.html/,
to: 'ReduxDataFlow\/exercise.html'
}
]
},
stats: {
// Config for minimal console.log mess.
assets: true,
colors: true,
version: true,
hash: true,
timings: true,
chunks: false,
chunkModules: false
}
}
}
This informaiton is coming from a training course, but they do not explain what the lines are doing.
Webpack is what we call a module bundler for JavaScript applications. You can do a whole slew of things with it that help a client browser download and run your code. In the case of React, it helps convert JSX code into plain JS so that the browser can understand it. JSX itself will not run in the browser. We can even use plugins to help minify code, inject HTML, bundle various groups of code together, etc. Now that the introduction to Webpack is out of the way, let's take a look at the code. I will be starting from the very top. Feel free to skip down to #3 if you are only interested in the Webpack configuration object.
The following code will require the modules that are needed in this file. fs is short for "filesystem" and is a module that gives you functions to run that can access the project's filesystem. path is a common module used to resolve or create pathnames to files and is very easy to use! And then we have the webpack module through which we can access webpack specific functions (ie: webpack plugins like webpack.optimize.UglifyJsPlugin).
const fs = require('fs')
const path = require('path')
const webpack = require('webpack')
These next few lines first set up a helper function to determine whether or not something in the filesystem being read is a directory.
function isDirectory(dir) {
return fs.lstatSync(dir).isDirectory()
}
const SubjectsDir = path.join(__dirname, 'subjects')
const SubjectDirs = fs.readdirSync(SubjectsDir).filter(function (dir) {
return isDirectory(path.join(SubjectsDir, dir))
})
devtool specifies which developer tool you want to use to help with debugging. Options are listed here : https://webpack.github.io/docs/configuration.html#devtool. This can be very useful in helping you determine exactly which files and lines and columns errors are coming from.
devtool: 'source-map'
These next few lines tell Webpack where to begin bundling your files. These initial files are called entry points. The entry property in a Webpack configuration object should be an object whose keys determine the name of a bundle and values point to a relative path to the entry file or the name of a node_module. You can also pass in an array of files to each entry point. This will cause each of those files to be bundled together into one file under the name specified by the key - ie: react and react-dom will each be parsed and have their outputs bundled under the name shared.
entry: SubjectDirs.reduce(function (entries, dir) {
if (fs.existsSync(path.join(SubjectsDir, dir, 'exercise.js')))
entries[dir + '-exercise'] = path.join(SubjectsDir, dir, 'exercise.js')
if (fs.existsSync(path.join(SubjectsDir, dir, 'solution.js')))
entries[dir + '-solution'] = path.join(SubjectsDir, dir, 'solution.js')
if (fs.existsSync(path.join(SubjectsDir, dir, 'lecture.js')))
entries[dir + '-lecture'] = path.join(SubjectsDir, dir, 'lecture.js')
return entries
}, {
shared: [ 'react', 'react-dom' ]
}),
In the reduce function we simply read through the SubjectsDir, determine whether files exercise.js, lecture.js & solution.js exist, and then provide the path to those files as values associated with the key names identified by dir + '-' + filename (ie: myDir-exercise). This may end up looking like the following if only exercise.js exists:
entry : {
'myDir-exercise': 'subjectDir/myDir/exercise.js',
share: ['react', 'react-dom']
}
After we provide entry points to the Webpack configuration object, we must specify where we want Webpack to output the result of bundling those files. This can be specified in the output property.
output: {
path: '__build__',
filename: '[name].js',
chunkFilename: '[id].chunk.js',
publicPath: '__build__'
},
The path property defines the absolute path to the output directory. In this case we call it __build__.
The filename property defines the output name of each entry point file. Webpack understands that by specifying '[name]' you are referring to the key you assigned to each entry point in the entry property (ie: shared or myDir-exercise).
The chunkFilename property is similar to the filename property but for non-entry chunk files which can be specified by the CommonChunksPlugin (see below). The use of [id] is similar to the use of [name].
The publicPath property defines the public URL to where your files are located, as in the URL from which to access your files through a browser.
The resolve property tells Webpack what how to resolve your files if it can not find them for some reason. There are several properties we can pass here with extensions being one of them. The extensions property tells Webpack which file extensions to try on a file if one is not specified in your code.
resolve: {
extensions: [ '', '.js', '.css' ]
},
For example, let's say we have the following code
const exercise = require('./exercise');
We can leave out the .js because we have provided that string in the resolve property of the webpack configuration and Webpack will try and append .js to this at bundling time to find your file. As of Webpack 2 we also no longer need to specify an empty string as the first element of the resolve property.
The module property tells Webpack how modules within our project will be treated. There are several properties we can add here and I suggest taking a look at the documentation for more details. loaders is a common property to use and with that we can tell Webpack how to parse particular file types within our project. The test property in each loader is simply a Regex that tells Webpack which files to run this loader on. This /\.js$/ for example will run the specified loader on files that end with .js. babel-loader is a widely used JavaScript + ES6 loader. The exclude property tells Webpack which files to not run with the specified loader. The loader property is the name of the loader. As of Webpack 2 we are no longer able to drop the -loader from the string as we see here.
Plugins have a wide range of functions. As mentioned earlier we can use plugins to help minify code or to build chunks that are used across our entire application, like react and react-dom. Here we see the CommonChunksPlugin being used which will bundle the files under the entry name shared together as a chunk so that they can be separated from the rest of the application.
Finally we have the devServer property which specifies certain configurations for the behavior of webpack-dev-server, which is a separate module from webpack. This module can be useful for development in that you can opt out of building your own web server and allow webpack-dev-server to serve your static files. It also does not write the outputs to your filesystem and serves the bundle from a location in memory at the path specified by the publicPath property in the output property of the Webpack configuration object (see #5). This helps make development faster. To use it you would simply run webpack-dev-server in place of webpack. Take a look at the documentation online for more details.
The configuration object that we've taken a look at follows the Webpack 1 standard. There are many changes between Webpack 1 and 2 in terms of configuration syntax that would be important to take a look at. The concepts are still the same, however. Take a look at the documentation for information on migrating to Webpack 2 and for further Webpack 2 details.

webpack configuration warnings and errors: "module parse failed"

I'm trying to build a simply application using the MEAN stack, and I'm running into an issue with Webpack. When I run "webpack" from the console, I get the following warnings and errors:
WARNING in ./~/require_optional/package.json
Module parse failed: C:\Build\myapp\node_modules\require_optional\package.json Unexpected token (2:9)
You may need an appropriate loader to handle this file type.
WARNING in ./~/require_optional/README.md
Module parse failed: C:\Build\myapp\node_modules\require_optional\README.md Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type.
WARNING in ./~/require_optional/LICENSE
Module parse failed: C:\Build\myapp\node_modules\require_optional\LICENSE Unexpected token (1:40)
You may need an appropriate loader to handle this file type.
ERROR in ./~/constants-browserify/constants.json
Module parse failed: C:\Build\myapp\node_modules\constants-browserify\constants.json Unexpected token (2:12)
You may need an appropriate loader to handle this file type.
So my questions are:
1. Should Webpack even be trying to load files like README.md and LICENSE? Why would it care about those?
2. I have a json-loader hooked up and looking for .json files, so why am I still getting warnings and errors about those?
Here's my Webpack config file:
webpack.config.js
var config = require('./environment/shared.js')
var debug = config.env !== 'production';
var webpack = require('webpack');
module.exports = {
context: __dirname,
devtool: debug ? 'inline-sourcemap' : null,
entry: './public/js/app.js',
output: {
path: __dirname + '/public/js',
filename: 'bundle.min.js',
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
module: {
loaders: [
{
test: '/\.json/',
loader: 'json',
},
{
test: '/\.node$/',
loader: 'node-loader',
},
],
},
resolve: {
extensions: ['', '.js', '.json', '.node'],
},
};
question 1:
I think there is something like following in your codebase. namely, require a module whose name is in a variable. In this case, webpack don't know exactly which module you are requiring, so it will load all file.
const moduleName = xxx
const module = require(moduleName)
question 2:
you need to add { test: /\.json$/, loader: "json" } in module/loaders for loading json file.

Categories

Resources