I was trying to run webpack-4 first time
webpack ./src/js/app.js ./dist/app.bundle.js
it shows warning / error :
WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/concepts/mode/
ERROR in multi ./src/js/app.js ./dist/app.bundle.js
Module not found: Error: Can't resolve './dist/app.bundle.js' in 'D:wamp64wwwwebpack-4'
@ multi ./src/js/app.js ./dist/app.bundle.js
Then i tried to change the mode
webpack --mode development
it shows :
ERROR in Entry module not found: Error: Can't resolve './src'
Slim
5,17711 gold badges46 silver badges78 bronze badges
asked Apr 11, 2018 at 10:36
Sabir HussainSabir Hussain
2,7122 gold badges13 silver badges19 bronze badges
1
Resolved
Spent a lot of time to find out the solution.
Solution: Add index.js
file into src
folder.
That’s it!.. solved
During Research, I found some facts about webpack 4 :
webpack 4 doesn’t need a configuration file by default!
webpack 4 there is no need to define the entry point: it will take ./src/index.js
as the default!
toastal
1,03810 silver badges16 bronze badges
answered Apr 11, 2018 at 10:36
Sabir HussainSabir Hussain
2,7122 gold badges13 silver badges19 bronze badges
4
Met this problem when deploying on now.sh
Solution: Use Default Behavior
Move entry point to src/index.js
.
This leverage webpack@4
default value for entry
:
By default its value is
./src/index.js
, but you can specify a
different (or multiple entry points) by configuring the entry property
in the webpack configuration.
Solution: Be Specific
As @Lokeh pointed out, if you don’t want to change your JS file location you can always use path.resolve()
in your webpack.config.js
:
entry: path.resolve(__dirname, 'src') + '/path/to/your/file.js',
answered Nov 23, 2018 at 11:18
Édouard LopezÉdouard Lopez
38.7k27 gold badges122 silver badges175 bronze badges
2
Adding a context explicitly in webpack.config.js fixed issue for me. Adapt the following piece of code in your project:
context: __dirname + '/src',
entry: './index.js',
brance
1,1188 silver badges22 bronze badges
answered May 18, 2020 at 13:17
webpack ./src/js/app.js --output ./dist/app.bundle.js --mode development
This worked for me. I had the same trouble, it is because of a new version of webpack
Stephen Rauch♦
46.7k31 gold badges109 silver badges131 bronze badges
answered Aug 8, 2018 at 0:47
ladhariladhari
4854 silver badges15 bronze badges
webpack version 4.46.0
Perhaps someone gets stuck during migration from webpack 4 to 5.
in case of multiple webpack config files and if anyone uses merge
:
Say webpack.common.js
relies on some variables
passed from cli
eg:
module.export = (env) => {
const {myCustomVar} = env;
return {
// some common webpack config that uses myCustomVar
}
}
When you require common config in say webpack.prod.js
:
const { merge } = require('webpack-merge'); // <-- `merge` is now named import if you are using > v5
const common = require('./webpack.common.js');
const getProdConfig = () => {....}
module.exports = (env) => {
return merge(common(env), getProdConfig()); // <-- here, `call` common as its exported as a fn()
};
answered Jan 3, 2022 at 11:01
YEVYYEVY
9921 gold badge9 silver badges16 bronze badges
2
I had a similar error and was able to resolve it with the command webpack src/index.js -o dist/bundle.js
the -o
did the trick. The issue wasn’t the location of index.js it was missing the operator for defining the output path location.
See https://webpack.js.org/api/cli/
Version of webpack was 4.44.1
answered Sep 14, 2020 at 1:22
JamesJames
1165 bronze badges
Other solutions didn’t work. I solved this by adding this to package.json
"scripts": {
"test": "echo "Error: no test specified" && exit 1",
"build": "webpack" //this
},
Then npm run build
and it works. At first i’ve tried with npx webpack
. Would love to know why it works.
answered Jun 15, 2022 at 19:12
Bar AkivaBar Akiva
1,0311 gold badge11 silver badges21 bronze badges
Just leaving this here, incase someone is not paying attention to the details like me, I had the same error, but because my webpack config file was named webpack.config instead on webpack.config.js, so my custom configurations were never picked and webpack was falling back to the defaults entry «src/index.js»
answered Jan 25, 2022 at 15:46
As of webpack ^4.29.6 you don’t need any configuration file so instead of giving path in package.json we need to write simply «build»: «webpack» and keep index.js as entry point in src folder. However if you want to change entry point you can do so in webpack config file
answered Mar 19, 2019 at 6:03
For Rails 6 application this steps worked for me:
1) bundle exec rails webpacker:install
system will reinstall webpacker but will rewrite few files:
modified: config/webpack/environment.js
modified: config/webpacker.yml
modified: package.json
modified: yarn.lock
2) Return configs to initial state:
git checkout config/webpack/environment.js
git checkout config/webpacker.yml
package.json
and yarn.lock
you can leave as they are
answered Jun 4, 2020 at 2:13
Spent a lot of time similarly to others to get around this annoying problem. Finally changed webpack.config.js
as follows:-
output: {
path: path.resolve(__dirname, './src'), //src instead of dist
publicPath: '/src/', //src instead of dist
filename: 'main.js' //main.js instead of build.js
}
…as Edouard Lopez and Sabir Hussain mentioned that you don’t need to mention an entry point, removed that also and the app compiled after a long frustration.
mechnicov
10.2k3 gold badges24 silver badges49 bronze badges
answered Jul 28, 2020 at 6:10
So my problem, which I would wager is a lot of people’s problem is that I set the entry path based on my whole app root. So in my case, it was /client/main.ts. But because my webpack.config.js file was actually inside /client, I had to move into that folder to run webpack. Therefore my entry was now looking for /client/client/main.ts.
So if you get this error you need to really look at your entry path and make sure it is right based on where you are running webpack and where your webpack.config.js file is. Your entry path needs to be relative to where you are running webpack. Not relative to your app root.
answered Sep 13, 2020 at 1:31
LeftOnTheMoonLeftOnTheMoon
8831 gold badge7 silver badges15 bronze badges
I had this problem when changing between React/Rails gems. Running rails webpacker:install
restored me to the Rails webpacker defaults, but also overwrote all of my config files. Upon closer inspection, the culprit turned out to be my webpack/development.js
file, which in a previous gem version had gotten modified from this Rails webpacker default:
process.env.NODE_ENV = process.env.NODE_ENV || 'development'
const environment = require('./environment')
module.exports = environment.toWebpackConfig()
Once I restored the file to those contents, this error went away. Specifically I had been missing the module.exports = environment.toWebpackConfig()
line, which apparently is pretty important for those who want to avoid Rails webpacker thinking it needs a src/index.js file (it doesn’t)
answered Nov 28, 2020 at 15:08
wbhardingwbharding
3,8552 gold badges28 silver badges25 bronze badges
Describe the bug
I have the following project folder structure:
my-app/ ├─ .webpack/ │ ├─ index.js │ ├─ development.js │ ├─ production.js ├─ node_modules/ ├─ src/ │ ├─ index.tsx ├─ package.json
When I use .webpack/index.js
to import a specific environment configuration I get the following error:
ERROR in main Module not found: Error: Can't resolve './src' in '/Users/<path-to-project>/my-app'
To Reproduce
package.json
"@webpack-cli/serve": "^1.0.1-rc.0", "webpack": "^5.0.0-rc.0", "webpack-cli": "^4.0.0-rc.0", "webpack-dev-server": "^3.11.0"
.webpack/index.js
module.exports = (env, arg) => { const { mode } = arg; const config = require(`./${mode}`); return config; };
.webpack/development.js
module.exports = { entry: path.resolve(__dirname, '../src/index.tsx'), output: { path: path.resolve(__dirname, '../build/'), filename: 'index.js' }, devtool: 'source-map', devServer: { inline: true, port: 8080, contentBase: path.resolve(__dirname, '../src') }, module: { rules: [ { test: /.tsx?$/, loader: 'awesome-typescript-loader' } ] }, resolve: { modules: [ '/Users/<path-to-project>/my-app/src', 'node_modules' ], extensions: ['.wasm', '.mjs', '.js', '.jsx', '.ts', '.tsx', '.json'], } };
> webpack serve --config .webpack/index.js --mode development
Expected behavior
Expected the src
directory to be resolved. If instead .webpack/index.js
has the configuration there is no error that shows up.
Please paste the results of webpack-cli info
here, and mention other relevant information
System: OS: macOS 10.15.6 CPU: (8) x64 Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz Memory: 451.53 MB / 16.00 GB Binaries: Node: 14.5.0 - ~/.nvm/versions/node/v14.5.0/bin/node Yarn: 1.22.4 - /usr/local/bin/yarn npm: 6.14.8 - ~/.nvm/versions/node/v14.5.0/bin/npm Browsers: Firefox: 81.0 Safari: 14.0 Packages: case-sensitive-paths-webpack-plugin: ^2.3.0 => 2.3.0 clean-webpack-plugin: ^3.0.0 => 3.0.0 extract-css-chunks-webpack-plugin: ^4.7.5 => 4.7.5 html-webpack-plugin: ^4.5.0 => 4.5.0 webpack: ^5.0.0-rc.0 => 5.0.0-rc.0 webpack-cli: ^4.0.0-rc.0 => 4.0.0-rc.0 webpack-dev-server: ^3.11.0 => 3.11.0 webpack-merge: ^5.1.4 => 5.1.4
Содержание
- ERROR in main Module not found: Error: Can’t resolve ‘./src’ in #16028
- <>’s edit
- Replies: 3 suggested answers · 1 reply
- <>’s edit
- <>’s edit
- [Solved] Module not found: Error: Can’t resolve
- Fix: add a dot-slash ( ./ ) before any relative path in webpack
- Conclusion
- Что значит эта ошибка, которая выдается в консоли при попытке подключить webpack?
- webpack: Failed to compile. #1
- Comments
- В чем ошибка сборки webpack?
ERROR in main Module not found: Error: Can’t resolve ‘./src’ in #16028
<>’s edit
Hello! This is the first time I am using webpack. I decided to use it instead of create-react-app, but right now I am facing what seems to be a very difficult problem with webpack: I am getting the following error:
And here is the screenshot:
I find this error peculiar because I don’t have any src folder in my project.
I tried to identify the error several times but it has got really hard for me to find a fix. Could you please help me?
Here is my repo: https://github.com/Yokubjon-J/chat-app (I run my app with npm run development ).
Beta Was this translation helpful? Give feedback.
1 You must be logged in to vote
经过我运行你的项目 我发现在经过compile函数的时候 获取的webpackconfig 配置是空的 进而报错。 当我修改完毕后 你的webpack.config.client文件的配置 传递给webpack函数 配置会报错 现在没有具体发现是哪一行。 但是你上边贴图的错算是解决了 。 因此对于你上边的图报错 原因就是 传递给webpack参数为<> 。
After I run your project, I find that the ‘webpackConfig’ parameter obtained when I pass the compile function is empty, and then an error is reported. When I finish modifying your webpack config. When the configuration of the client file is passed to the webpack function, an error will be reported. At present, no specific line of configuration has been found. But the mistake of your upper mapping is solved. Therefore, the reason for the error in the above figure is that the parameter passed to webpack is <>.
btw if function does nothing you can module.exports = config;
Beta Was this translation helpful? Give feedback.
1 You must be logged in to vote
<>’s edit
<>’s edit
Unfortunately, I am still getting an error, but this time it is slightly different:
Beta Was this translation helpful? Give feedback.
I guess that the error is caused because webpack is not generating dist/bundle.js file, which template.js references: https://github.com/Yokubjon-J/chat-app/blob/no-cra/template.js#L10. template.js is in turn served by express.
@vankop could you please point out why webpack is not generating bundle.js .
Beta Was this translation helpful? Give feedback.
1 You must be logged in to vote
经过我运行你的项目 我发现在经过compile函数的时候 获取的webpackconfig 配置是空的 进而报错。 当我修改完毕后 你的webpack.config.client文件的配置 传递给webpack函数 配置会报错 现在没有具体发现是哪一行。 但是你上边贴图的错算是解决了 。 因此对于你上边的图报错 原因就是 传递给webpack参数为<> 。
After I run your project, I find that the ‘webpackConfig’ parameter obtained when I pass the compile function is empty, and then an error is reported. When I finish modifying your webpack config. When the configuration of the client file is passed to the webpack function, an error will be reported. At present, no specific line of configuration has been found. But the mistake of your upper mapping is solved. Therefore, the reason for the error in the above figure is that the parameter passed to webpack is <>.
Beta Was this translation helpful? Give feedback.
Источник
[Solved] Module not found: Error: Can’t resolve
This webpack error occurs when you don’t put a ./ in front of a relative path. For example, npx webpack index.js should be npx webpack ./index.js .
While I was first getting started on my journey of learning webpack from scratch, I came across this error almost immediately. The funny thing is, I was doing something I thought was innocent enough. I mean, most command line applications understand what you mean when you reference a file without a path leading up to that file. It means “this file is right here, in the current working directory”.
But for some reason, webpack can’t handle that. It’s just too much stress for it I guess, and it’s already had a long day. So you have to be very careful not to do something to make it work harder than it has to, and risk setting it off. Because you’ve seen its error messages before – they’re straight up monsters. It’ll barf out 200 lines of nonsense because of one tiny mistake, with the first or second line of the error message being the actual problem and the rest being junk.
Anyway, I naively ran the following command:
That’ll work, right? Why wouldn’t it? WRONG. I got the following beast of an error instead:
You’d think I did something much worse than just forget a leading ./ ! The key above is in the highlighted line – webpack just really doesn’t like relative paths that don’t start with a dot-slash.
As for the rest of the error, it looks like what happens is, webpack traverses every parent directory looking for index.js . I mean, thanks, I guess. You really made sure to check everywhere before failing. I do appreciate the tenacity and resourcefulness. But you forgot to check in the most important place of all – THE CURRENT WORKING DIRECTORY. But I digress.
Fix: add a dot-slash ( ./ ) before any relative path in webpack
That’s right, the solution is simply to add a dot-slash ( ./ ) before any path you feed to webpack. That is, if it’s relative. If it’s an absolute path, like /home/user/index.js , you’re just fine because there’s no question which file you’re referring to.
In my case, I just changed my command to:
And then it worked:
Don’t worry about the warning about ‘mode’ not being set. That’s a whole separate issue. What I care about at this point is that it actually compiled. Good job!
Note that you’ll need to add the dot-slash to every relative file that webpack sees, hears, reads, smells, or touches. That means when you graduate to having a webpack.config.js file, you’ll need to use dot-slashes in all relative file paths in there too.
Conclusion
We covered what causes “Module not found: Error: Can’t resolve (whatever)” in webpack. The bottom line is, webpack hates relative paths that don’t start with a dot-slash. Like, really hates them. Hates them so much that it’ll spew out a 60 line error code looking in every parent folder of your current directory saying how it can’t find the file there either. It’s almost like it’s being sarcastic.
Anyway, problem is solved, hopefully you never run into this error again. If you do, just come back here and re-read all this.
About the Author
Bill is a senior software engineer with 23 years of experience. He specializes in Python, Javascript, C/C++, DevOps, test driven development, and making sure your code isn’t terrible.
Источник
Что значит эта ошибка, которая выдается в консоли при попытке подключить webpack?
Всем привет. Пытаюсь подключить вебпак и постоянно при запуске команды npm run build получаю вот такую ошибку и пустой файл bundle.js:
asset bundle.js 99 bytes [emitted] (name: main)
ERROR in main
Module not found: Error: Can’t resolve ‘.src/index.js’ in ‘C:UsersUserDesktopПроектыMim’
resolve ‘.src/index.js’ in ‘C:UsersUserDesktopПроектыMim’
Parsed request is a module
using description file: C:UsersUserDesktopПроектыMimpackage.json (relative path: .)
Field ‘browser’ doesn’t contain a valid alias configuration
resolve as module
looking for modules in C:UsersUserDesktopПроектыMimnode_modules
C:UsersUserDesktopПроектыMimnode_modules.src doesn’t exist
C:UsersUserDesktopПроектыnode_modules doesn’t exist or is not a directory
C:UsersUserDesktopnode_modules doesn’t exist or is not a directory
C:UsersUsernode_modules doesn’t exist or is not a directory
C:Usersnode_modules doesn’t exist or is not a directory
C:node_modules doesn’t exist or is not a directory
webpack 5.72.0 compiled with 1 error in 69 ms
Структура сайта:
Mim
-dist/bundle.js
-node_modules
-src/index.js
-index.html
-package-lock.json
-package.json
-webpack.config.js
Может кто знает в чем проблема? Подскажите, пожалуйста
Источник
webpack: Failed to compile. #1
- npm install
- npm install -g webpack
- cd path/to/example
- run webpack-dev-server (after npm install webpack-dev-server -g)
I receive this error in each of the example folders:
/webpack-dev-server/client?http://localhost:8080 webpack-dev-server/client?http://0.0.0.0:8080 webpack/hot/only-dev-server ./main.js webpack: Failed to compile.
If I change loaders: [‘babel’] to loaders: [‘babel-loader’] in the webpack.config.js file it output webpack: Compiled successfully. however it does actually not compile. And there is no browser output for index.html.
Running MacOS with node v6.10.0, webpack 2.2.1, webpack-dev-server 2.4.1.
The text was updated successfully, but these errors were encountered:
I’ve been playing a similar whack-a-mole game. 🐰 I did a few things slightly differently, but arrived at the same result: nothing is output to the browser. After realizing that running npm install in the top-level folder had already installed webpack-dev-server locally, I uninstalled the global package and tried to run the local copy like so:
So I did what the error message suggested and edited webpack-config.js like so:
After that, running the same command spit out 264 lines of text ending with:
Everything looked fine, and I was ready to do my victory dance, but. all I’m seeing is a blank page when I open localhost:8080 . This is the case for the hello-jsx and builtin-html-tags examples, at least. (I didn’t check the others, but I suspect it will be true of all the examples.)
Some version info, in case it’s helpful in diagnosing the problem:
UPDATE
I tried the other suggestion from one of the node error messages, namely:
we recommend that you remove «react-hot-loader» from the «loaders» section of your Webpack configuration altogether, and instead add «react-hot-loader/babel» to the «plugins» section of your .babelrc file.
The end result was the same: it appeared to be working (no error messages, server running and responding to requests), but I’m seeing an entirely blank page in my browser.
I realized, after running git status a few times, that the examples repo contains a node_modules folder that winds up showing a bunch of changes after I run npm install from the top-level. So I tried this, on a whim:
Alas, it had no effect. I still get empty pages. Oh, well. I can’t afford to spend any more time on it today. This is really frustrating. The book seems to be really well-written, and I like the engaging, clear style of presentation. But I’m dead in the water on the very first example.
It seems that the Compatibility Hell of JS frameworks hasn’t changed much since the last time I dipped my toe in that pond. I know people who’ve been doing web development for years that can finger-mumble their way out of problems like this in just a few minutes, but. I’m an embedded systems engineer trying to learn this stuff on a lark. So far, it’s. not as fun as I’d hoped. 😞
How does one even begin to troubleshoot a problem like this?
Источник
В чем ошибка сборки webpack?
Простой 4 комментария
s_katala, содержимое ваших файлов webpack.config.js и package.json. Найти их можно в корневой папке проекта.
Только сбрасывайте как код в тег code (троеточие на панели форматирования комментария).
Замените babel на babel-loader:
Ну а по-хорошему перепишите конфиг по-современному:
Ну вы очень старый конфиг используете. А webpack третий.
Антон Спирин,
с url решил
теперь вот так
s_katala, используется устаревшая библиотека https://github.com/lingochamp/react-qiniu не совместимая с вашим кодом.
Выпиливайте ее. Тем более она для какого-то китайского CDN написана, которым вы вряд ли будете пользоваться https://www.qiniu.com
Я не пойму вы какой-то чужой старый проект скачали и пытаетесь запустить?
Источник
Привет witcher4680,
Очень похоже что dev server запускается без файла конфигурации. Кстати есть два варианта devserver’a на основе легкого koa он же serve про который написала Eva Rosalene и на основе более тяжелого Express, который используете Вы. Сравнительную статью можно найти тут Development Servers Compared: Webpack-Dev-Server Vs. Webpack-Serve. Что интересно оба этих веб фреймворка делает одна команда программистов.
witcher4680, я посоветую Вам попробовать следующие варианты:
1 Запустить webpack-dev-server без параметров из папки где лежит webpack.config.js, он должен прочитать файл конфигурации и запустить сервер без открытия браузера
2 Запустить webpack-dev-server с опцией —config ./webpack.config.js
3 Можно попробовать дополнительно указать опцию publicPath, но это просто предложение никогда не использовал эту опцию.
Если ошибка пропала попробовать добавить опцию open с указанием конкретного браузера, хотя конечно в документации написано что будет запущен браузер по умолчанию.
Добавлено через 1 час 11 минут
Сообщение от web_coder2
Кстати есть два варианта devserver’a на основе легкого koa он же serve про который написала Eva Rosalene и на основе более тяжелого Express, который используете Вы. Сравнительную статью можно найти тут Development Servers Compared: Webpack-Dev-Server Vs. Webpack-Serve. Что интересно оба этих веб фреймворка делает одна команда программистов.
Но кажется уже все поменялось =) и сейчас webpack-dev-server и webpack serve это одно и тоже
Добавлено через 5 минут
Просто я никогда не пользовался командой webpack-dev-server, а потом меня переклинило ее искать и попал на статью, а потом только посмотрел как webpack-dev-server ставить и как serve оказалось абсолютно одинаково. Вот так вот.
ERROR in Entry Module not found: ERROR: Can’t resolve ‘./ SRC ‘in’ E: DocumentsVSCode filesWebPackProject ‘
Specify the inlet and outlet through the configuration file
Js (must be in the project root directory)
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
}
};
Not packaged by configuration file
By default, Webpack4 does not need to create webpack.config.js to configure the packaged entry and exit.
By default,
The entry is ./ SRC /index.js
file
Exit to ./dist/main.js
file
Directory structure:
Js is in the correct position. Run the command in the project root directory:
webpack
You are ready to pack.
So now you can see that under the project directory, dist
folder, you’ll see the packaged file main.js
;
In the HTML file index. HTML
which needs to be introduced, it can be correctly introduced.
You can also specify it manually using the following command:
webpack./SRC /index.js -- output-filename. /dist/main.js --output-path. --mode development
or
webpack ./src/index.js -o ./dist/main.js --mode development
note:
, --mode development
is the specified development mode, without which warning will be reported;
Another mode is --mode production
specifies the production mode. In this mode, the packaged js file will be compressed, but the former will not.
Webpack will prompt a warning when executing directly from above. Closing the warning can be packaged by the following command:
webpack --mode development
or
webpack --mode production
`
Read More:
- ERROR in Entry module not found Error Can t resolve
- Error in entry module not found: error: can’t resolve ‘Babel loader’
- Module not found: Error: Can’t resolve ‘sass-loader’ in ‘F:H5project-h5’
- Module not found:Error:Can’t resolve ‘rc-animate/lib/CSSMotionList’ in ‘……’
- npm start:Module not found: Error: Can’t resolve ‘xlsx’ in ‘/Users/huzhiqi/Downloads/web/…
- Module not found: Error: Can’t resolve ‘./$$_gendir/app/app.module.ngfactory’
- Error: can’t resolve ‘FS’ in (webpack 2 configures CSS loaders)
- NPX webpack cannot find module’html webpack plugin’a bug causes headache
- ./src/router/index.js Module not found: Error: Can‘t resolve ‘@/views/tet_demo‘ in ‘D:adminsrcrou
- Webpack Upgrade Error: webpack.NamedModulesPlugin is not a constructor
- Webpack error module build failed: typeerror: fileSystem.statSync is not a function
- Run webpack error: Error: Cannot find module’webpack/lib/node/NodeTemplatePlugin’
- Has HTML webpack plugin been installed, or error: cannot find module ‘HTML webpack plugin’
- Error: unable to resolve dependency for… Could not resolve project
- Cannot find module ‘webpack cli / bin / config yargs‘
- Failed to load bundle…Unable to resolve module `xxx` from xxx: Module `xx` does not exist
- Error: Cannot find module’webpack/bin/config-yargs’ solution
- Solved – problem cannot find module ‘webpack / bin / config yargs’
- Error: cannot find module ‘webpack / lib / ruleset’_ solve
- [Solved] Error: Cannot find module ‘webpack/lib/RequestShortener’
You want to build only Express and gql server-related files separately using webpack5.
However, an error occurs when building.
ERROR in main
Module not found: Error: Can’t resolve ‘./src’ in’/Users/leedonghee/Dropbox/Project/observer/Homepage/v2/server
My files don’t use ./src anywhere.
Dir
server(root)
├─ dist
├─ model(mongoose & gql)
│ ├─ schema.js
│ └─ main-sliders
│ ├─ model.js
│ ├─ resolver.js
│ └─ schema.graphql
├─ node_modules
├─ index.js
├─ webpack.config.js
├─ .babelrc
├─ .env
├─ package.json
├─ package-lock.json
└─ ...
package.json
{
"name": "server",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"dev:server": "NODE_ENV=development nodemon --exec babel-node index.js",
"build": "webpack --mode production --progress",
"start:server": "NODE_ENV=production node ./build/index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"core-js": "^3.8.1",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-graphql": "^0.12.0",
"graphql": "^15.4.0",
"graphql-tools": "^7.0.2",
"merge-graphql-schemas": "^1.7.8",
"mongoose": "^5.11.7",
"path-browserify": "^1.0.1",
"regenerator-runtime": "^0.13.7"
},
"devDependencies": {
"@babel/cli": "^7.12.10",
"@babel/core": "^7.12.10",
"@babel/node": "^7.12.10",
"@babel/preset-env": "^7.12.11",
"babel-loader": "^8.2.2",
"clean-webpack-plugin": "^3.0.0",
"nodemon": "^2.0.6",
"webpack": "^5.10.3",
"webpack-cli": "^4.2.0",
"webpack-graphql-loader": "^1.0.2"
}
}
webpack.config.js
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const path = require("path");
module.export = {
entry: "index.js",
mode: "production",
target: "node",
resolve: {
modules: ["node_modules"],
extensions: [".js", ".json"],
fallback: { path: require.resolve("path-browserify") },
},
output: {
publicPath: "/",
path: path.resolve(__dirname, "build"),
filename: "index.js",
},
module: {
rules: [
{
test: /.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
},
{
test: /.graphql?$/,
use: [
{
loader: "webpack-graphql-loader",
options: {
minify: true,
},
},
],
},
],
},
plugins: [new CleanWebpackPlugin()],
};
index.js
import express from "express";
import dotenv from "dotenv";
import cors from "cors";
import mongoose from "mongoose";
const { graphqlHTTP } = require("express-graphql");
import schema from "./models/schema";
import "core-js/stable";
import "regenerator-runtime/runtime";
const app = express();
// env --------------------------------------------
dotenv.config();
const { PROD_PORT, DEV_PORT, DB_NAME, DB_URI, NODE_ENV } = process.env;
const port = NODE_ENV === "development" ? DEV_PORT : PROD_PORT;
// DB Setting --------------------------------------------
mongoose.Promise = global.Promise; // db서버 비동기처리
mongoose.connect(DB_URI, {
useNewUrlParser: true,
useFindAndModify: false,
useCreateIndex: true,
useUnifiedTopology: true,
});
mongoose.connection.once("open", () =>
console.log(`???? Connected to "${DB_NAME}" MongoDB server.`)
);
mongoose.connection.on("error", (error) => console.error(`???? Error: :`, error));
// Get React Build File --------------------------------------------
const homepage = require("path").join(__dirname, "..", "homepage", "build");
app.use(express.static(homepage));
app.get("/", (req, res) => {
res.sendFile("index.html", { homepage });
});
app.use(
"/graphql",
cors(),
graphqlHTTP({
schema: schema,
graphiql: NODE_ENV === "development" ? true : false,
})
);
app.listen(port, () => {
console.log(
`n???? Server running on http://localhost:${port}n${
NODE_ENV === "development" ? "⚙️ Development" : "???? Production"
} mode`
);
});
.babelrc
{
"presets": [
["@babel/preset-env" ,
{
"useBuiltIns" : "usage" ,
"corejs" : 3
}]
]
}
Resolved
Spent a lot of time to find out the solution.
Solution: Add index.js
file into src
folder.
That’s it!.. solved
During Research, I found some facts about webpack 4 :
webpack 4 doesn’t need a configuration file by default!
webpack 4 there is no need to define the entry point: it will take ./src/index.js
as the default!
Met this problem when deploying on now.sh
Solution: Use Default Behavior
Move entry point to src/index.js
.
This leverage [email protected]
default value for entry
:
By default its value is
./src/index.js
, but you can specify a
different (or multiple entry points) by configuring the entry property
in the webpack configuration.
Solution: Be Specific
As @Lokeh pointed out, if you don’t want to change your JS file location you can always use path.resolve()
in your webpack.config.js
:
entry: path.resolve(__dirname, 'src') + '/path/to/your/file.js',
webpack ./src/js/app.js --output ./dist/app.bundle.js --mode development
This worked for me. I had the same trouble, it is because of a new version of webpack
Tags:
Npm
Webpack
Webpack 4
Related
When I run the ‘webpack’ command, I get this error:
ERROR in ./js/main.js
Module not found: Error: Can’t resolve ‘jquery’ in ‘…js’ @ ./js/main.js 3:0-16 4:0-23
In package.json I have:
"devDependencies": {
"handlebars": "^4.0.6",
"handlebars-loader": "^1.4.0",
"jquery": "^3.2.1",
"path": "^0.12.7"
},
in webpack.config.js:
var path = require("path");
module.exports = {
entry: "./js/main.js",
output: {
path: __dirname + "/js",
filename: "scripts-bundled.js"
},
resolve: {
modules: [
path.join(__dirname, "js/helpers")
]
},
module: {
loaders: [
{test: /.hbs$/, loader: "handlebars-loader"}
]
}
};
and in main.js at the top of the file, I have:
import $ from 'jquery';
I’m also using handlebars in main.js. Could it be that handlebars or handlebars-loader is interfering with the jquery? I’ve used webpack and jquery without this issue before in another project where I didn’t use handlebars, but maybe it has nothing to do with it.