Unable to add alias to webpack.config - reactjs

I've created react app with create-react-app and I'm unable to add alias to resolve -> alias node in webpack.config.js located in node_modules/react-scripts/config:
Module not found: Can't resolve '#/_components' in 'c:\my-app\src\app'
alias: {
'#': path.resolve(__dirname, 'src/'),
Probably missing smth simple... Here are webpack docs: https://webpack.js.org/configuration/resolve/#resolvealias

once you use create-react-app the standard way to modify your webpack setting is to run npm run eject as stated docs and not modify directly at node_modules as you are trying to.
to avoid the ejecting command you could use a helper lib react-app-rewired which simplifies the process for overriding some default webpack configurations.
nevertheless, create-react-app offers the option to point absolute paths through a jsconfig.json file like stated in the docs reference which might suit you better:
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}

Related

Clean CRA not resolving #/absolute/paths

I have a completely clean install of create-react-app but when I try to use absolute paths it won't resolve the paths.
Everything seems correct since VSCode resolves the path successfully but the react app won't.
My tsconfig.file is also clean from npx create-react-app my-app --template typescript only extending to another tsconfig.path.json with the following:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"#/*": ["./src/*"]
}
}
}
Error:
Compiled with problems:X
ERROR in ./src/App.tsx 7:0-44
Module not found: Error: Can't resolve '#/features/Comp' in 'C:\Users\REDACTED\PROJECT_ROOT\src'
I've tried to created another project with CRA just to test and the same occurs.
Also using simply the baseURL:["src"] wont resolve in the App but VSCode Successfuly resolves.

Error Could not resolve entry module React + Rollup

I need to build shareable React component which could be used across apps.
For this, I was/am following the below article
https://dev.to/alexeagleson/how-to-create-and-publish-a-react-component-library
My Configuration looks exactly the same except the npm packages version (even tried with the same versions)
The folder structure looks the same as below
rollup.config.js
import resolve from "#rollup/plugin-node-resolve";
import commonjs from "#rollup/plugin-commonjs";
import typescript from "#rollup/plugin-typescript";
import dts from "rollup-plugin-dts";
const packageJson = require("./package.json");
export default [
{
input: "src/index.ts",
output: [
{
file: packageJson.main,
format: "cjs",
sourcemap: true,
},
{
file: packageJson.module,
format: "esm",
sourcemap: true,
},
],
plugins: [resolve(), commonjs(), typescript({ tsconfig: "./tsconfig.json" })],
},
{
input: "dist/esm/types/index.d.ts",
output: [{ file: "dist/index.d.ts", format: "esm" }],
plugins: [dts()],
},
];
npm script
"rollup": "rollup -c"
However when I run npm run rollup this throws the below error
[!] Error: Could not resolve entry module (dist/esm/types/index.d.ts).
Error: Could not resolve entry module (dist/esm/types/index.d.ts)
Please suggest. Thanks!
I also ran into the same problem you are experiencing when working with rollup. After spending some while digging for the solution, I finally got to solve this problem.
My Configuration looks exactly the same except the npm packages version (even tried with the same versions)
The exception you have stated is actually the problem. The problem lies in package versioning. The package #rollup/plugin-typescript versions later than 8.3.3 are not generating nor storing the declaration files in the types folder expected to be at the path: dist/cjs/ and dist/esm/.
The latest version at this point in time is 8.5.0 which still breaks. Hopefully it is fixed in near future.
Steps to fix your error
Make sure your tsconfig.json file has "declarationDir": "types" to direct the bundler's typescript plugin to create and store declaration files in the types folder when you run npm run rollup
Uninstall the existing #rollup/plugin-typescript package version by running npm un #rollup/plugin-typescript --save-dev
Install #rollup/plugin-typescript with the command npm i #rollup/plugin-typescript#8.3.3 --save-dev. As you see, we are picking a specific version.
If you still encounter problems:
Manually update the package.json file like: "#rollup/plugin-typescript": "8.3.3". Note that I have removed the caret(^) symbol to tie the package to version 8.3.3.
Delete the node_modules folder. You could use the command rm -rf node_modules.
Delete package-lock.json.
Run npm i to install the packages again with versions specified in package.json
Here's an working answer for people coming from 2023 that doesn't lock you to an outdated version of #rollup/plugin-typescript:
Preconditions: Make sure that you get rid off your package-lock.json and your node_modules directory so that you can start from a clean slate and install your project again.
run npm install tslib --save-dev
add "type": "module" to package.json
in tsconfig.json, add "rootDir": "src"
in rollup.config.js, change plugins: [dts()] to plugins: [dts.default()]
back in package.json, add --bundleConfigAsCjs as a parameter to the rollup command in scripts
After that you should be able to continue with the tutorial and be able to create a new build via npm run rollup.
I fixed the error of 'Could not resolve entry module (dist/esm/index.d.ts)'.
I tried removing types, downgrading react to match the version in the tutorial but none worked.
I found this comment on the tutorial which was helpful: https://dev.to/nasheomirro/comment/239nj
I got rid of main and common js set up in both rollup config and package json.
i changed the packagejson variable to import packageJson from "./package.json" assert { type: "json" };
added types back into the input in the rollup config
Set "#rollup/plugin-typescript" to be version "8.3.3" as mentioned above.
I now have a Dist folder with an ESM folder and didn't get any errors.

Absolute paths for React app on Github CI with Firebase hosting

After switching to use absolute paths, although my local builds still work fine, Github CI build fails with this error:
./src/App.js
Cannot find module: 'components/Layout'. Make sure this package is installed.
How can I make Firebase/Github CI also search the src directory?
Creating jsconfig.json with the following configuration should do the trick:
{
"compilerOptions": {
"baseUrl": "src"
},
"include": [
"src"
]
}
I've tried creating a sample repo with the setup you mentioned and GitHub actions (I hope this is what you meant by GitHub CI) job did create build properly.

Importing react app into existing Webpack project

I have a Rails app that uses Webpack to bundle its assets. It doesn't currently use React.
In a separate repository, I have created a React app. This React app basically implements a complex custom UI element. The plan is that I can import this react component into my main application.
So far I have added the git repo to my package.json file and can see that the source code of my react app is being downloaded into the /node_modules folder.
I can get Webpack to bundle the app by adding:
To the React app package.json:
"prepare": "npm run build"
And in my main application webpack.config
module.exports = {
...
resolve: {
...
alias: {
MyReactApp: 'my-react-app/dist/bundle.js'
}
}
}
But it seems to be bundling all the libraries that my React app uses inside bundle.js and not adding them to the dependency tree.
It appears that the prepare command is basically bundling my React app into a /dist/bundle.js file and Webpack is simply including this file as-is. I need Webpack to manage the dependencies of my React app, such that I don't have unnecessary libraries duplicated in the final Webpack output.
Is there a better way to achieve what I am trying to achieve?
It is better to bundle them together. Basically, it is trying to bundle already bundled code.
This may work:
resolve: {
alias: {
MyReactApp: 'my-react-app/index.js'
}
}
index.js should be main jsx starting point.
Additionally, you need to add compile rules for jsx files, I never bundled Rail apps but React apps you should follow these steps;
Add rule to webpack.config.js
module: {
rules: [
{
// this is so that we can compile any React,
// ES6 and above into normal ES5 syntax
test: /\.(js|jsx)$/,
// we do not want anything from node_modules to be compiled
exclude: /node_modules/,
use: ["babel-loader"]
},
...
]
}
Install Babel modules:
npm install #babel/core #babel/node #babel/preset-env #babel/preset-react babel-loader
create a file called .babelrc and paste the following code
{
"presets": ["#babel/env", "#babel/react"],
"plugins": ["#babel/plugin-proposal-class-properties"]
}
Run webpack though babel-node like following script
"webpack": "babel-node ./node_modules/webpack/bin/webpack"
This would be my approach to solve this problem. It will still import react to your project. But instead of adding the compiled project, it will add jsx files and will compile them during the bundling process.
Note:
babel/core this is used to compile ES6 and above into ES5
babel/node this is used so that we can import our plugins and packages inside the webpack.config.js rather than require them
(it’s just something that I like, and maybe you’ll like it too)
babel/preset-env this will determinate which transformations or plugins to use and polyfills (i.e it provides modern
functionality on older browsers that do not natively support it)
based on the browser matrix you want to support
babel/preset-react this is going to compile the React code into ES5 code
babel-loader this is a Webpack helper that transforms your JavaScript dependencies with Babel (i.e. will transform the import
statements into require ones)

Invalid Option: corejs is not a valid top-level option

I built react project with webpack and babel.
It worked well.
But, today I got some error below.
ERROR in ./index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: [BABEL] /home/rpf5573/react-discovery-v2/src/admin/admin-client/index.js: Invalid Option: corejs is not a valid top-level option.
Maybe you meant to use 'targets'? (While processing: "/home/rpf5573/react-discovery-v2/src/admin/admin-client/node_modules/#babel/preset-env/lib/index.js")
at validateTopLevelOptions (/home/rpf5573/react-discovery-v2/src/admin/admin-client/node_modules/#babel/preset-env/lib/normalize-options.js:49:13)
at normalizeOptions (/home/rpf5573/react-discovery-v2/src/admin/admin-client/node_modules/#babel/preset-env/lib/normalize-options.js:160:3)
at _default (/home/rpf5573/react-discovery-v2/src/admin/admin-client/node_modules/#babel/preset-env/lib/index.js:168:37)
....
error Command failed with exit code 2.
And this is my admin-client/.babelrc
module.exports = {
compact: true,
presets: [
[
"#babel/preset-env",
{
modules: false,
targets: {
browsers: ["since 2015"]
},
useBuiltIns: "usage",
corejs: "2"
}
],
"#babel/preset-react"
],
plugins: [
"#babel/plugin-proposal-class-properties"
]
}
What did I wrong ?
What should I do ?
Maybe you had some major version change recently?
In my case, that was the cause. And the solution was:
Completely remove node-modules folder from the project
Remove package-lock.json file from the project root folder
Perform a npm i to recreate everything
As an alternative to entirely deleting node-modules as suggested by #SysDragon. I looked deeper into why the complaint was specific to corejs. And i found a great remedy here.
In summary, these were the steps taken:
Install the latest version of core-js (or atleast version-3).
Whatever you are building "might" be making use of latest JavaScript functionality. For my case, i was working with react-16.9.0 and mdbreact-4.19.0.
Note: Core-js is a Modular standard library for JavaScript. Includes polyfills for ECMAScript up to 2019: promises, symbols, collections, iterators, typed arrays and many other features.
Then, you need to update your transpiler, babel and it's "relatives".
This block snippet helped accomplish that: yarn upgrade #babel/core #babel/plugin-transform-runtime #babel/polyfill #babel/preset-env #babel/runtime babel-loader --dev.
The --dev part is just to save them as devDependencies (if using yarn) (for npm, use --save-dev), which i advocate for especially if this is team project.
In my case, the subdirectory I was working on was part of a larger Yarn workspace in the root of the repository and removing that subdirectory from the workspace and reinstalling node_modules within the subdirectory fixed the issue.
This issue is most likely caused by dependency mismatches.

Resources