is there a way to automatically migrate all relative paths to alias paths in the entire project tree with webpack? - reactjs

I'm looking for a solution to replace all my relative imports "../../../" to alias paths I set in the webpack.config.js instead of manually replacing the strings.
I'm working in a React JS project that is large enough that I feel there must be a way to automatically resolve all relative paths to alias paths in all modules and files.
Appreciate your help if you have any experience with this scenario.
My webpack config is already setup with this:
resolve: {
alias: {
js: path.resolve(__dirname, 'js'),
css: path.resolve(__dirname, 'css')
}
},

Related

How to make a path alias in CRA TypeScript in 2022?

I just initiated CRA npx create-react-app my-app --template typescript and I want to make an alias when calling components, like:
import components from '#components'
where the components is located at src/components.
I've tried to config in tsconfig.json by adding:
{
"compilerOptions": {
...
"baseUrl": "./src",
"paths": {
"#utils/": ["./utils/"],
"#utils/*": ["./utils/*"]
}
}
}
Also in webpack.config.js by adding:
// const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin')
const path = require('path')
module.exports = {
resolve: {
// plugins: [new TsconfigPathsPlugin()],
alias: {
'#utils': path.resolve(__dirname, './src/utils/'),
'#utils/*': path.resolve(__dirname, './src/utils/*')
}
}
}
But it's still doesn't work.
Anyone could help me to solving these problem? But, I don't wont to use other libraries like #craco/craco.
The issue is that CRA uses its own Webpack config under the hood. Simply making a new webpack.config file doesn't actually point CRA to it, unless you run npm run eject.
Doing so is irreversible, but will add the config files to your project. From there, you should be able to modify your build settings to fit your needs.
Reminder that this cannot be undone in your project, barring perhaps a git reset, and may be more than you bargained for.
This issue with aliases seems to be a known one. Something people deemed possible earlier seems to no longer be working, or supported. Some people are speculating this could have something to do with the recent update of Webpack to version 5. And while some people claim that craco doesn't work for them, I was able to get it to work in a brand new CRA app with minimal changes. I know you're not interested in that so I won't post it here.
Alternatively, CRA allows the use of absolute imports via the src baseUrl. This will point both VSCode and Webpack to your final files, but you won't be able to set up custom paths.
"baseUrl" : "."
Using multiple index.ts files and exporting nested code up to the highest level in the directory, I'm able to keep the import paths as short as an alias:
import { persistor, store } from "src/state-management";
This could be good enough for you. If not, consider adding a package to override some of CRA's Webpack settings, or ejecting and taking matters into your own hands.

Why .js [file Extension] is not added while importing a component in reactJS?

We are creating different components in reactJS,
Example:
App.js
index.js
LandingPage.js
.....
While importing this component in another component, we are not adding the extension .js
Example:
index.js:
import App from './App'
// here './App' we are not adding .js
Does anyone know the reason why?
Your Webpack config is taking care of resolving the common extensions (ie: .js or .jsx). If your project is using create-react-app, then this is already done for you behind the scenes.
Create-react-app already resolves the following extensions automatically:
extensions: [".web.js", ".mjs", ".js", ".json", ".web.jsx", ".jsx"],
More info here
https://github.com/webpack/docs/wiki/Configuration#resolveextensions
It all done by webpack module resolution, a resolver is a library which helps in locating a module by its absolute path.
The dependency module can be from the application code or a third-party library. The resolver helps webpack find the module code that needs to be included in the bundle for every such require/import statement. webpack uses enhanced-resolve to resolve file paths while bundling modules.
Once the path is resolved based on the above rule, the resolver checks to see if the path points to a file or a directory. If the path points to a file:
If the path has a file extension, then the file is bundled straightaway.
Otherwise, the file extension is resolved using the resolve.extensions option, which tells the resolver which extensions are acceptable for resolution e.g. .js, .jsx.
Resolve extensions: These options change how modules are resolved. webpack provides reasonable defaults, but it is possible to change the resolving in detail.
In webpack.config.js
module.exports = {
//...
resolve: {
enforceExtension: false
}
};
If the value is true here, it will not allow extension-less files. So by default require('./foo') works if ./foo has a .js extension, but with this (enforceExtension) enabled only require('./foo.js') will work.
Add .js to resolve/extensions in webpack.config.js
resolve: {
extensions: [".ts", ".js", ".mjs", ".json"],
symlinks: false,
cacheWithContext: false,
},

Plugin system for apps compiled using Webpack

For the context: I'm developing my own product using Symfony on the back-end and react/react-router on the front-end, which is tied together by Webpack. I'm planning to divide my app into "extensions", so I would have "core" bundle and multiple different extending bundles around it (which would be sets of additional features for my product).
Now, I would like for my front-end to be as extensible as my back-end. I would like to be able to add new React components with my extending bundles to the existing "core" set of components in my "CoreBundle".
However, it seems like the Webpack is encapsulating everything too tightly to be able to produce that kind of a plugin system. Is it possible to have multiple bundles that would have separate Webpack configurations, but their JavaScript would be interconnected in a way that would allow for developing of a plugin system? The goal is being able to develop JS of one Bundle independently but at the same time being able to use some already compiled JS resources from another Bundle in the process.
I think you should be able to achieve this using the DllPlugin and the DllReferencePlugin
The DllPlugin is used in a separate webpack config to create a dll
only bundle. It also creates a manifest.json file which is used by the
DllReferencePlugin to map dependencies.
Refer to the detailed documentation at
https://webpack.js.org/plugins/dll-plugin/
In my case, I use this to combine all vendor libraries (React, Flux, etc) in one build and then use that as a reference in my Other Webpack Config which bundles all my React components etc. but references React and other libraries using the DllReferencePlugin.
My webpack.dll.js config file:
var path = require("path");
var webpack = require("webpack");
module.exports = {
entry: {
libs: [path.join(__dirname, "common", "lib.js")]
},
output: {
path: path.join(__dirname, "dist", "dll"),
filename: "[name].dll.js",
library: "[name]"
},
plugins: [
new webpack.DllPlugin({
path: path.join(__dirname, "dll", "[name]-manifest.json"),
name: "[name]",
context: path.resolve(__dirname, "common")
}),
]
};
And then in my main webpack.config.js, I use the reference plugin.
new webpack.DllReferencePlugin({
context: path.resolve(__dirname, "common"),
manifest:require('./dll/libs-manifest.json')
})
Depending upon how you want to split your code, you can create multiple Dlls, each with a separate webpack config as per your requirements. And then refer the dll's as per your requirements in different other webpack bundles.

How to point assets and html angular templates folder after building angularjs with webpack?

i am new to webpack, i have configured webpack to a working condition where my index.html file and budle.js file comes to /dist folder. iam aware that i can build css files too but for now i want to build js and run the app. please check the attached images for better understanding of the directory structure and the webpack build configuration.
My doubt is that if i run app from dist folder i would lose all the path of angular templates and image paths etc. how can i overcome this situation? any help is appreciated.
First of all, you need to know that the goal is to have a fully runnable stand alone application inside ./dist/ after build. All sourcefiles which are needed to run your application should be placed there. In that way you will be able to distribute your application by copy/upload/or-what-ever based on your ./dist/ directory. All other directories in your project are just for development. Those will be not a part of your distribution package.
Wrong approach: Trying to change the include path's in your application.
You need to copy or concat your sourcefiles (static files) into your distribution folder. I realy don't know why your views/templates are not stored in ./app/assets/ and not in ./app/views/ because ./app/views/ should be the correct path to store your views. Well, you need to copy your static sourcefiles. For example: You could use copy-webpack-plugin.
Your webpack config could look like this in the end:
var CopyWebpackPlugin = require('copy-webpack-plugin');
var path = require('path');
module.exports = {
context: path.join(__dirname, 'app'),
devServer: {
// This is required for older versions of webpack-dev-server
// if you use absolute 'to' paths. The path should be an
// absolute path to your build destination.
outputPath: path.join(__dirname, 'dist')
},
plugins: [
new CopyWebpackPlugin([
{
from: 'assets/**/*',
to: 'assets/'
},
{
from: 'views/**/*',
to: 'views/'
},
], {
ignore: [
],
// By default, we only copy modified files during
// a watch or webpack-dev-server build. Setting this
// to `true` copies all files.
copyUnmodified: true
})
]
};

data structure of reactjs built project

I am new to react, redux and webpack and I have several problems. I started with "simpe-redux-boilerplate". My project structure is:
--src
--containers
--index.js
--...
--php
--vendor
--janguage.json
First, I need to use janguage.json from my App.js in container directory without bundling, so I am not importing it but fetching
fetch('language.json')...
I am able to import it with path './../../language.json', but for fetching this path is not working. Which is the right path?
Second, I am using php for server requests (php and other directories). Unfortunately, these directories are not included in my build. How to add them? Move to src directory doesn't work.
My webpack prod configuration:
entry: [
'./src/index',
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/'
},...
Thank you.

Resources