I am kinda new in the web and would like to ask a simple question.
Basically I just want to eliminate dots from my import. I mean thing like:
import Component from '../../container/etc'
How could I just start my import from the root? So its would become smth like:
import Component from 'container/etc'
I used create-react-app for set up
You can add the resolve config in webpack like
module.exports = {
//things here
resolve: {
extensions: ['.jsx', '.scss', '.js', '.json'],
modules: [
path.resolve(__dirname, 'app'),
'node_modules'
]
}
// other things here
}
where you directory structure would be like
-- app
-- container
-- etc.js
-- api.json
so you can import like
import ETC from 'container/etc';
import json from 'api.json'
In case you are using create-react-app, you can create a .env file on the root of your project and make the NODE_PATH point to the src folder (or wherever you have your code) all you'll have to do is write:
NODE_PATH=src
Create-react-app will read your .env file without ejecting.
Related
I built an Vue 3 app (+ Vite) which I want to also convert to an Electron app. Every time I start the Electron app via electron . it looks like the SVG isn't getting packaged: (Navigation Drawer with missing icons)
Upon further investigation this is the case, but in my dist folder all images are available. (SVGs are in the dist folder) But the Devtools show that they don't get into the Electron app. (Electron app asset folder)
I also implemented the workaround for changing the base path in the Vite config like this (The Electron ENV gets set before I run electron . via a npm script):
import { fileURLToPath, URL } from "url";
import { defineConfig } from "vite";
import vue from "#vitejs/plugin-vue";
import path from "path";
// https://vitejs.dev/config/
export default defineConfig({
base:
// eslint-disable-next-line no-undef
process.env.ELECTRON == "true" ? path.resolve(__dirname, "./dist/") : "./",
plugins: [vue()],
resolve: {
alias: {
"#": fileURLToPath(new URL("./src", import.meta.url)),
},
},
assetsInclude: ["**/*.svg"],
});
Does anyone have an idea what the problem might be? Thanks in advance!
UPDATE
I got it working after all by following this example: https://github.com/pengYYYYY/vite-electron. Also a base tag was missing in my index.html.
Like that: <base href="./" />
How can i use #import to import my components in my scripts from other folders in my react project.
For example i have a folder structure like this
src
|
--- App.jsx
|
--- pages
| |___ home.jsx
|
|
--- components
|__ HomeComponent.jsx
How can i use in home.jsx
import HomeComponent from "#components/HomeComponent"
if i just try to use import HomeComponent from "#components/HomeComponent" like
this i get error module not found.
You can do a relative import from pages/home.jsx like this
import HomeComponent from "../components/HomeComponent"
Here ../ means you are going up one directory level and then into components directory
You can also perform absolute imports by setting up additional tools like babel or webpack. An absolute import would look like this when you have set src as your root directory
import HomeComponent from "components/HomeComponent"
If you are using create-react-app, this setup is easy to do as all the tooling is already handled by create-react-app
You can read about it here under the absolute imports section - https://create-react-app.dev/docs/importing-a-component/
babel-plugin-module-resolver
This plugin can simplify the require/import paths in your project. For example, instead of using complex relative paths like ../../../../utils/my-utils, you can write #utils/my-utils. It will allow you to work faster since you won't need to calculate how many levels of directory you have to go up before accessing the file.
// Use this:
import MyUtilFn from 'utils/MyUtilFn';
// Instead of that:
import MyUtilFn from '../../../../utils/MyUtilFn';
// And it also work with require calls
// Use this:
const MyUtilFn = require('utils/MyUtilFn');
// Instead of that:
const MyUtilFn = require('../../../../utils/MyUtilFn');
Install the plugin
npm install --save-dev babel-plugin-module-resolver
or
yarn add --dev babel-plugin-module-resolver
Specify the plugin in your .babelrc with the custom root or alias. Here's an example:
{
"plugins": [
["module-resolver", {
"root": ["./src"],
"alias": {
"test": "./test",
"underscore": "lodash"
}
}]
]
}
.babelrc.js version
Specify the plugin in your .babelrc.js file with the custom root or alias. Here's an example:
const plugins = [
[
require.resolve('babel-plugin-module-resolver'),
{
root: ["./src/"],
alias: {
"test": "./test"
}
}
]
];
Good example: https://gist.github.com/nodkz/41e189ff22325a27fe6a5ca81df2cb91
Currently I have an import which looks like this
import Button from "../../../components/Button/Button"
but I want to make it relative so I wouldn't require to type the ../../../ time and again.
I want to import using this method:
import Button from "components/Button/Button" or src/components/Button/Button
but please also assure that it will work on both production and development.
If you are using vscode with project created with create-react-app you can try adding a jsconfig.json file in root with this .
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
If you are using webpack. You can use resolve.
const path = require('path');
module.exports = {
//...
resolve: {
alias: {
Utilities: path.resolve(__dirname, 'src/utilities/'),
Templates: path.resolve(__dirname, 'src/templates/'),
Components: path.resolve(__dirname, 'src/components/'),
}
}
};
Now, instead of using relative paths when importing like so:
import Utility from '../../utilities/utility';
import Button from '../../src/components/Button';
you can use the alias:
import Utility from 'Utilities/utility';
import Button from 'Components/Button';
you can download the react snippet plugig to help you with import
import Butoon from './component/Button/Button' I Think
I'm trying to get imports like
import { startup } from "applicationRoot/renderUI";
to work, from anywhere in my application. I thought the rollup-plugin-alias would be a good fit for this. I tried configuring
alias({
applicationRoot: "applicationRoot/"
})
in my plugins array. This came close, but the extension is dropped, so I get the error:
c:\path\to\applicationRoot\renderUI doesn't exist.
Adding in
alias({
resolve: [".js"],
applicationRoot: "applicationRoot/"
}),
did not change anything.
You can use rollup-plugin-includepaths.
Add this to your Rollup configuration:
import includePaths from 'rollup-plugin-includepaths';
export default {
...
plugins: [
...
includePaths({ paths: ["./"] })
]
};
That will tell Rollup to also resolve imports from the root of your application, so things like
import { startup } from "applicationRoot/renderUI";
will appropriately find an applicationRoot folder where it is.
This is not the answer to the original question, but if you are coming here from search results and are using Typescript, you can set the compilerOptions.baseUrl in tsconfig and it will just work.
{
...
compilerOptions: {
...
"baseUrl": "./"
},
}
Then if you have a file like `src/lib/util.ts' you can import it:
import util from 'src/lib/util'
We would like to create bundle.js from React and webpack, where a per build configuration is included and made available to the React code, but we are not sure how to go about doing this.
The idea would be to be to do something like:
npm run build -- config="config123.json"
And then have the generated bundle.js include that configuration, such that it could be used by the root container. Something like:
import React from 'react';
import ReactDOM from 'react-dom';
import RootContainer from './containers/main-container';
ReactDOM.render(
<RootContainer config={configPassedByBuildProcess}/>,
document.getElementById('app')
);
Is this possible and if so, how should we approach this?
No, I don't believe that you can pass a file on build, from what I know the only thing that you can pass is a string like an ENV variable. You could import the config123.json file like this
import React from 'react';
import ReactDOM from 'react-dom';
import RootContainer from './containers/main-container';
import config from '/path/to/config123.json'
ReactDOM.render(
<RootContainer config={config}/>,
document.getElementById('app')
);
You may need a JSON loader for importing JSON files
After a bit of experimenting, the solution I have found is to use Webpack's DefinePlugin, since this provides a way of doing string substitution during webpack's build phase.
In my React code I defined:
// Will be substituted by webpack's DefinePlugin. Not an error.
const bundleConfig = BUNDLE_CONFIG;
and then in my webpack.config.js I first load my config (hard coded for now):
// The path can be pulled in via 'process.args' and parsed as appropriate
const bundleConfig = fs.readFileSync('bundle-config/default-config.json', 'UTF-8');
module.exports = {
plugins: [
new webpack.DefinePlugin({
'BUNDLE_CONFIG': bundleConfig
})
]
}
Note that if for some reason we want to build with a missing or undefined bundleConfig, then the right substitution would likely be the string (not the keyword) 'undefined' , to keep the code valid, such that:
const bundleConfig = 'undefined';
module.exports = {
plugins: [
new webpack.DefinePlugin({
'BUNDLE_CONFIG': bundleConfig
})
]
}
Just one extra thing was the configuration of the package.json (scripts section only):
{
"scripts": {
"build": "run() { NODE_ENV=production && webpack -p $1; }; run",
}
}
This allow passing in the path to the webpack.conf.js script, when we call:
npm run build /path/to/config.json