Why am I getting Webpack 'module not found' error? - javascript

I am refactoring project which has a working webpack bundling. Basically, I am trying to change the root source folder of the project and I am having an issue. I have been debugging for so long but I cannot see what I am missing.
In my tsconfig.json file I have the following settings
"baseUrl": "./",
"paths": {
"src/*": [
"src/*"
],
"test/*": [
"test/*"
]
}
In the webpack.common.js file I have the following
const includePaths = ['node_modules', 'src'];
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx'],
modules: includePaths,
},
My source folder is in the root of my project. Basically I should be able to reach with ./src
This is how I bundle:
rm -rf ./build && webpack --config webpack.dev.js
webpack.dev.js
merge(common, config, {
entry: {
main: [
`${__dirname}/src/environment`,
'webpack-hot-middleware/client?path=__webpack_hmr&dynamicPublicPath=true',
`${__dirname}/src/main`,
],
},
When I run the bundler in watch mode I see something like:
These dependencies were not found:
src/<somefolder>/<somefile> in ./src/<somefolder>/<somefile.tsx>
Module not found: Error: Can't resolve ...
The weird thing is, when src folder was under another folder eg. frontend/src, it was bundling without an issue. I suspect something is off in the tsconfig but I cannot figure it out. Can someone please help?

Adding alias like this worked but I don't really understand how old version was working without the alias.
alias: {
src: path.resolve(__dirname, 'src'),
},

Related

Are typescript project references necessary if transpiling with babel? (Electron project with Webpack)

I am still in the process of setting up my project configuration so I don't have any errors to work with right now, but if I am understanding the Typescript docs correctly...
It seems like Project references TypeScript Docs - Project references are not that necessary if transpiling with babel-loader in webpack. (I'm working in VSCode)
I am trying to convert an Electron app to TypeScript and currently reorganizing the folder structure so I have minimal issues.
I am trying to understand if I am on the right track and if I can avoid including "references" and instead just use "extends" to get the functionality I want.🤔
Here is my project structure ignoring all files that are not tsconfig files:
./tsconfig.json
./tsconfig-base.json
./main/tsconfig.json
./src/client/tsconfig.json
./__tests__
./__tests__/__client__/tsconfig.json
./__tests__/__main__/tsconfig.json
In this structure ./tsconfig.json would really just be for references like the example on Microsoft's Github
Electron Main Process and related files are in ./main. The tsconfig here will set "module":"commonjs" for working in node. I think it will also extend from the ./tsconfig-base.json
Electron Renderer Process and my React-Redux app files are in ./src/client. The tsconfig here sets "module":"es2015" or "module":"ESNEXT" for working with es modules. I think it will also extend from the ./tsconfig-base.json
The ./__tests__/__client__/tsconfig.json and ./__tests__/__main__/tsconfig.json would just be duplicates of the non tests folder versions similarly extending from the base config in ./
Webpack config is already set up to handle creating separate bundles for main and renderer processes so that the entire app can be in TypeScript. Is there any reason I should be using "references" in my files in the main or client folders?
Sample snippets of the Webpack config before I switch the tnry files to be .ts files (dev):
const rendererInclude = path.resolve(__dirname, "src");
const mainInclude = path.resolve(__dirname, "main");
Main Process:
module.exports = [
{
mode: "development",
entry: path.join(__dirname, "main", "swell.js"),
output: {
path: path.join(__dirname, "dist"),
filename: "main-bundle.js",
},
target: "electron-main",
node: {
__dirname: false,
__filename: false,
},
resolve: {
extensions: [".ts", ".tsx", ".js", ".json"],
},
module: {
rules: [
{
test: /\.(ts|js)x?$/,
loader: "babel-loader",
include: mainInclude,
exclude: /node_modules/,
}
] } ... },
continued to Renderer Process:
{
mode: "development",
entry: path.join(__dirname, "src", "index.js"),
output: {
path: path.join(__dirname, "dist"),
filename: "renderer-bundle.js",
},
target: "electron-renderer",
resolve: {
extensions: [".ts", ".tsx", ".js", ".json"],
},
module: {
rules: [
{
test: /\.(ts|js)x?$/,
loader: "babel-loader",
include: rendererInclude,
exclude: /node_modules/,
]} ...} ]
Project Reference will help you solve some problems in case where your test projects import src/main modules.
This is what Project Reference solves:
There’s no built-in up-to-date checking, so you end up always running tsc twice
Invoking tsc twice incurs more startup time overhead
tsc -w can’t run on multiple config files at once
read more about Project References

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 2 with bower

I'm currently working on project, which depends partialy on 'bower only' dependencies and I need somehow to add bower_components module to Webpack 2 bundle. How can I do it? Documentation from previous version doesn't work and bower-webpack-plugin is outdated. I'm using Webpack#2.2.1.
I added this code to webpack.config.js:
resolve: {
extensions: ['.js', '.jsx'],
modules: ['bower_components', 'node_modules']
}
But unfortunately this doesn't work.
Use current version of documentation
Correct resolving of path to bower_components with path module had helped me. Maybe it will helps you.
Webpack2 can be used with bower with resolving options, you can read more here: https://gist.github.com/sokra/27b24881210b56bbaff7#resolving-options
A simple example of webpack.config.js resolving a bower.json file:
module.exports = {
entry: './file.js',
output: {
filename: 'my-first-webpack.bundle.js'
},
resolve: {
modules: [ "bower_components"],
descriptionFiles: ["bower.json"]
}
};

npm link with webpack - cannot find module

I'm trying to npm link a module to a project using webpack as its bundler. Of course, after trying many things, I keep getting this error:
ERROR in ./src/components/store/TableView.jsx
Module not found: Error: Cannot resolve module 'react-bootstrap-table'
Here are the exact steps I take when doing this:
1.) cd ../forks/react-bootstrap-table
2.) npm link
(success, checked ~/.nvm/.../node_modules/react-bootstrap-table for symlink and it's there)
3.) cd ../../projRoot/
4.) npm link react-bootstrap-table
(no errors thrown?, says successful link)
5.) node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js
Solutions I've tried:
- https://webpack.github.io/docs/troubleshooting.html
- How to make a linked component peerDepdencies use the equivalent node_modules of the script being linked to?
- And many purple links on google serps
webpack.config.js
const webpack = require('webpack')
const path = require('path')
const ROOT_PATH = path.resolve(__dirname)
module.exports = {
devtool: process.env.NODE_ENV === 'production' ? '' : 'source-map',
entry: [
'webpack/hot/only-dev-server',
'./src/index.js'
],
module: {
loaders: [{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['react-hot','babel']
},
{
test: /\.scss$/,
loaders: ['style','css','sass'],
exclude: /node_modules/
},
{
test: /\.css$/,
loaders: ['style','css']
},
{
test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
loader: 'file-loader'
}
]
},
resolve: {
extensions: ['', '.js', '.jsx'],
fallback: path.resolve(__dirname, './node_modules')
},
resolveLoader: {
fallback: path.resolve(__dirname, './node_modules')
},
output: {
path: process.env.NODE_ENV === 'production' ? path.resolve(ROOT_PATH, 'app/dist') : path.resolve(ROOT_PATH, 'app/build'),
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: path.resolve(ROOT_PATH),
historyApiFallback: true,
hot: true,
inline: true,
progress: true,
stats: 'errors-only',
host: '192.168.1.115'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
]
}
Notes:
1. this is the only symlink in the project
2. I run npm install inside forked version (also tried without, doesn't work)
3. I use NVM, but I have used symlinks before without webpack successfully.
I've been at this for a few days now, any help will be much appreciated.
I was facing a similar issue with webpack and ended up by adding this my webpack.config.js:
module.exports = {
resolve: {
symlinks: false
}
};
Here is the link to webpack docs. Since your question there happened a lot to webpack and their api, so I do not know how much relevance my answer still has according to your question. But for people facing this or a similar issue today this could be a solution. As to be seen, there are still people complaining about:
Webpack GitHub Issue 1643
Webpack GitHub Issue 1866
Also make sure you have bundle and yarn installed and executed in the linked package
Okay guys, this is specific to my use case, but make sure to follow all the instructions to completely build the library you are symlinking. Initially, I a npm install and gulp build, but that wasn't enough. I had to run a few extra commands to get the library to fully build.
Now it works! If you are still having issues, go through the documentation for each library you are symlinking, and use my webpack config as a template for resolving external libraries.
Just in case it's useful for others, the solution of adding the resolve.symlinks configuration to false suggested by #Beat was not enough in my case, I had to perform the following steps to solve it:
In the library:
Setup the libraries that are generating issues as peerDependencies in the package.json instead of dependencies or devDependencies, e.g. in my case react:
"peerDependencies": {
"react": "^16.8.6",
...
}
run npm install
build the library (in my case, with a rollup -c npm script
In my main app:
change the version of my library to point to my local project with a relative path in package.json, e.g.
"dependencies": {
"my-library": "file:../../libraries/my-library",
...
}
Add resolve.symlinks = false to my main app's webpack configuration
Add --preserve-symlinks-main and --preserve-symlinks to my package.json start script, e.g:
"scripts": {
"build": "set WEBPACK_CONFIG_FILE=all&& webpack",
"start": "set WEBPACK_CONFIG_FILE=all&& webpack && node --preserve-symlinks-main --preserve-symlinks dist/server.js",
}
run npm install
run npm run start

Categories

Resources