Use absolute path in React components - javascript

How I can use absolute path from root and change root, for import components?
import Modal from project/app/src/Components/Modal
import Main from ../../../../Constants
and I want, change root directory to I can import from src
import Modal from Components/Modal
import Main from Constants
I try change workspaces in package.json
"workspaces": [
"project/app/src/*"
]
or use
"scripts": {
"start": "NODE_PATH=project/app/src/ webpack-dev-server"
}
but it's not working.

.env file with NODE_PATH=src is deprecating.
use jsconfig.json in root dir instead
{
"compilerOptions": {
"baseUrl": "./src"
}
}

To implement absolute imports in create-react-app First you need to Create a ‘.env’ file at the root level (same level as package.json) then Set an environment variable, ‘NODE_PATH’ to ‘src/’
NODE_PATH=src

Related

How to use absolute/dynamic paths in NodeJs

Would like to use imports by using absolute/dynamic paths, like
import { GlobalVars } from "utils/GlobalVars.js";
but not like
import { GlobalVars } from "../../utils/GlobalVars.js";
With the help of below code snippet able to follow absolute/dynamic path facility in react
jsconfig.json (Which is created at root level of the project)
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
with the same code snippet unable to use absolute paths in NodeJs.
Do we have any other approach to use absolute paths in NodeJs or am i doing any mistake

How to make an import shortcut/alias in create-react-app?

How to set import shortcuts/aliases in create-react-app?
From this:
import { Layout } from '../../Components/Layout'
to this:
import { Layout } from '#Components/Layout'
I have a webpack 4.42.0 version.
I don't have a webpack.config.js file in the root directory. I've tried to create one myself with this code inside:
const path = require('path')
module.exports = {
resolve: {
alias: {
'#': path.resolve(__dirname, 'src/'),
}
}
};
But it doesn't seem to work. I've seen the NODE_PATH=. variant in .env file. But I believe, it is deprecated - better not to use. And also, I have a posstcss.config.js file. Because I've installed the TailwindCss and I import the CSS library there. I've tried to paste the same code there, but it also didn't work.
It is finally possible with Create React App v.3
Just put:
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
into jsconfig.json or tsconfig.json if you use Typescript
Here is wonderful article about this.
Simplest way to archive this follow below steps. (same way as #DennisVash showed as but in simple form)
Installation - install and setup CRACO.
yarn add #craco/craco
# OR
npm install #craco/craco --save
Create a craco.config.js file in the root directory and configure CRACO:
/* craco.config.js */
const path = require(`path`);
module.exports = {
webpack: {
alias: {
'#': path.resolve(__dirname, 'src/'),
'#Components': path.resolve(__dirname, 'src/components'),
'#So_on': path.resolve(__dirname, 'src/so_on'),
}
},
};
Update the existing calls to react-scripts in the scripts section of your package.json file to use the craco CLI:
/* package.json */
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test"
}
Done! Setup is completed.
Now let's test it.
// Before
import Button from "./form/Button"
import { Layout } from '../../Components/Layout'
// After
import Button from "#/form/Button"
import { Layout } from '#Components/Layout'
Documentation Craco
Thank you. :)
// Absolute path: paths which are relative to a specific path
import Input from 'components' // src/components
import UsersUtils from 'page/users/utils' // src/page/users/utils
// Alias path: other naming to specific path
import Input from '#components' // src/components
import UsersUtils from '#userUtils' // src/page/users/utils
In order for webpack's aliases to work, you need to configure the default webpack.config.js of create-react-app.
The official way is to use the eject script.
But the recommended way is to use a library without ejecting (find the most modern library for that).
VSCode IntelliSense
In addition, you should add jsconfig.json file for path IntelliSense in VSCode (or tsconfig.json), see followup question.
Now such code with IntelliSense will work:
// NOTE THAT THOSE ARE ALIASES, NOT ABSOLUTE PATHS
// AutoComplete and redirection works
import {ColorBox} from '#atoms';
import {RECOIL_STATE} from '#state';
If you want to use:
// this:
import MyUtilFn from 'utils/MyUtilFn';
// Instead of this:
import MyUtilFn from '../../../../utils/MyUtilFn';
use the node module plugin for resolving the urls https://www.npmjs.com/package/babel-plugin-module-resolver. By installing it and adding it to your webpack/babel.rc file.
Step 1
yarn add --dev babel-plugin-module-resolver
add this plugin
Step 2
in babel.config.js file
ALIAS NAME ALIAS PATH
#navigation ./src/navigation
#components ./src/components
#assets ./assets
[
"module-resolver",
{
root: ["./src"],
alias: {
"^~(.+)": "./src/\\1",
},
extensions: [
".ios.js",
".android.js",
".js",
".jsx",
".json",
".tsx",
".ts",
".native.js",
],
},
];
Step 3
import example
import SomeComponent from '#components/SomeComponent.js';
Step 4
restart server
yarn start
Reference link: How to use import aliases with React native and VSCode

Calling file from different folder / source in my project

I have 2 sources in my project. How can I import a file from MyProject in nest-project-payment?
This is the file structure of my project:
Tried using the following import statement:
import { User } from "MyProject/src/entity/User";
import { User } from "../../../MyProject/src/entity/User";
With ../ you move one folder up.
If you want to use an import like in your example, make the following change to your tsconfig.json file:
"baseUrl": "./",
"paths": {
"#nest-project-payment/*": ["nest-project-payment/*"],
"src/*": ["src/*"]
}

Creating a tree shakable library with rollup

I am trying to create a component library wie rollup and Vue that can be tree shakable when others import it. My setup goes as follows:
Relevant excerpt from package.json
{
"name": "red-components-with-rollup",
"version": "1.0.0",
"sideEffects": false,
"main": "dist/lib.cjs.js",
"module": "dist/lib.esm.js",
"browser": "dist/lib.umd.js",
"scripts": {
"build": "rollup -c",
"dev": "rollup -c -w"
},
"devDependencies": {
/* ... */
}
And this is my entire rollup.config.js
import resolve from "rollup-plugin-node-resolve";
import commonjs from "rollup-plugin-commonjs";
import vue from "rollup-plugin-vue";
import pkg from "./package.json";
export default {
input: "lib/index.js",
output: [
{
file: pkg.browser,
format: "umd",
name: "red-components"
},
{ file: pkg.main, format: "cjs" },
{ file: pkg.module, format: "es" }
],
plugins: [resolve(), commonjs(), vue()]
};
I have a fairly simple project structure with an index.js file and 2 Vue components:
root
∟ lib
∟ index.js
∟ components
∟ Anchor.vue
∟ Button.vue
∟ package.json
∟ rollup.config.js
My index.js imports the Vue files and exports them:
export { default as Anchor } from "./components/Anchor.vue";
export { default as Button } from "./components/Button.vue";
export default undefined;
If I don't do export default undefined; somehow any app importing my library cannot find any exports. Weird.
Now when I create another app and I import red-components-with-rollup like so:
import { Anchor } from "red-components-with-rollup";
and I open the bundle from my app, I will also find the source code of the Button.vue in my bundle, it has not been eliminated as dead code.
What am I doing wrong?
What is the build result of the ES format? Is it a single file or multiples, similar to your sources?
Considering your Rollup options, I’m guessing it bundles everything into a single file, which is most probably the reason it isn’t able to tree-shake it.
To keep your ES build into multiple files, you should change:
{ file: pkg.module, format: "es" }
Into:
{
format: "es",
// Use a directory instead of a file as it will output multiple
dir: 'dist/esm'
// Keep a separate file for each module
preserveModules: true,
// Optionally strip useless path from source
preserveModulesRoot: 'lib',
}
You’ll need to update your package.json to point module to the new build file, something like "module": "dist/esm/index.js".
There are some interesting pitfalls with tree shaking that this article covers that you might be interested in.
Other than that - does your build tooling for your consumer app support pure es modules and have tree shaking capabilities? If so, then i would just make sure your exported files are not doing any 'side-effecty' things that might confuse rollup.
To be on the safe side i would offer direct imports to for each of your components as well as one main index.js that exports them. At least you're giving people who are paranoid of shipping unused code the option ie -
import { Anchor } from "red-components-with-rollup/Anchor";

How can I organize my Angular app folders like a Java package?

How to organize Angular 2 app folder structure like Java packages?
Consider the following project layout:
app
|_model
|_component
|_service
I would like to import foo.service.ts from service to bar.component.ts in component. But as far as I know, Angular 2 import supports only relative paths like /../service/, which seems very clunky solution.
Is there a way to refer folders with absolute bath from root folder, like with Java packages?
UPDATE 2016-06-01
using npm install typescript#next you can already use this function
I assume that your tree looks like this:
node_modules
|_#angular
|_rxjs
app
|_model
|_component
|_service
package.json
tsconfig.json
You should add in your tsconfig.json the following lines:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"*": [
"app/*",
"node_modules/*"
]
}
}
}
then you can reference your modules like you do with regular #angular/rxjs modules
import { MyService } from 'service/MyService';
import { Component } from '#angular/core';
import { Observable } from 'rxjs';
Note: webpack needs also the following lines in webpack.config.js
resolve: {
modulesDirectories: [
'node_modules',
'app'
]
}
Not yet, it should be present soon with Typescript 2.0
Look here
https://github.com/Microsoft/TypeScript/issues/5039

Categories

Resources