Relative Imports in React.js - javascript

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

Related

vue.config.js configureWebpack not used in unit tests (vue 3)

In my vue config I have the following:
configureWebpack: {
resolve: {
alias: {
react: path.resolve(__dirname, 'composition/react'),
hooks: path.resolve(__dirname, 'composition'),
},
},
},
In my component I have the following:
import { useEffect, useState } from 'react';
This is so I can re use some of the Vue code in React projects. This works when running and building the project but not when testing. When unit testing I get the error: Cannot find module 'react' from 'useCategories.js', the above import is from useCategories.
The following is in the jest.config.js:
module.exports = {
preset: '#vue/cli-plugin-unit-jest',
transform: {
'^.+\\.vue$': 'vue-jest'
}
}
If unit testing in vue is ignoring values from vue.config.js then how can I set the webpack path resolve values for testing. I would rather not repeat these values but if it's a JavaScript file I guess I can import it from the same file in different configs.
Webpack isn't used in Jest, this would make module testing impractical, so Webpack config cannot affect anything.
As the documentation explains, it's necessary to provide module mapping in Jest config as well, e.g.:
moduleNameMapper: {
'^react$': '<rootDir>/composition/react',
...

Use index file to export .tsx modules

It's a common thing to create a index.js file in an React application with the only purpose to export several modules, in order to avoid having too many import statements on other components. This can be done by:
index.js
export { Credits } from './Credits.js';
export { SocialMedia } from './SocialMedia.js';
any module that might use those exports:
import * as var_name from index.js
And this is very nice. It wraps exports into a single file. However, when I changed my project to React with typescript, I found that .tsx files cannot be exported like that. The image below is the error I got after changing the project to typescript and the extensions became .tsx
Is there a way of 'bundle' export React .tsx files with the structure shown above? If not, what is the simplest way of centralizing .tsx files export?
My webpack.config.js:
module.exports = {
module: {
rules: [{
test: /\.scss$/,
use: ["sass-loader"]
}]
}
};
You can definitely use the same style of having an index file to group up exports for a whole folder. The simplest way around your problem would be to omit the file extension (assuming you only have one "index" file in the folder).
For example, let's say you have a component in 'common/Example.tsx':
import React from 'react'
export const Example = () => (<div>I'm an example component</div>)
You can then export it in an index file 'common/index.tsx':
export { Example } from './Example'
And import it from somewhere else, e.g. 'App.tsx':
import { Example } from './common'

Build React components library with Webpack 4

I'm currently building a library of React components and bundling it with Webpack 4.
Everything works just fine from building the library's bundle to publishing it on an npm registry.
But then, I'm not able to import any of its components in an other React application and get this error message at runtime:
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
And here is the related code:
A dumb component from my components library:
button/index.js
import React from "react";
const Button = () => <button>Foobar</button>;
export { Button };
The main entry point of my library index.js:
import { Button } from "./src/components/Button";
export { Button };
My Webpack config webpack.config.js:
const path = require("path");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
module.exports = {
entry: "./index.js",
plugins: [new CleanWebpackPlugin()],
module: {
rules: [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
},
output: {
filename: "index.js",
path: path.resolve(__dirname, "dist"),
libraryTarget: "commonjs",
library: ""
}
};
And finally, the import of this component in an other application:
import { Button } from "my-design-system";
I guess I'm missing something in my Webpack config or one of the property may be wrong, but after reading multiple posts and tutorials, I can't figure which one.
You're exporting your library as commonjs and trying to import it via import/export syntax. You should change your output to
output: {
filename: "index.js",
path: path.resolve(__dirname, "dist"),
libraryTarget: "umd",
library: "my-design-system"
}
Found a lot of info here: https://webpack.js.org/guides/author-libraries/
What I would do is to export your components as default and then re-export as named from index.js:
/// Button.js
import React from "react";
const Button = () => <button>Foobar</button>;
export default Button ;
// index.js
export { default as Button } from "./src/components/Button";
Then you can do
import { Button } from "my-design-system";
Also make sure you have main set up, pointing to your index.js, in your design system's package.json
Additionally, if you still want to have named exports in some of your components, you can export everything from that component file:
//index.js
export * from "./src/components/ComponentWithNamedExports";
Either way you will make sure there's always one point of export for all your components.
EDIT: As noted in by Maaz Syed Adeeb, you have wrong libraryTarget in your config. I'd remove both libraryTarget and library from there.

React eliminate dots from import

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.

Absolute imports with rollup

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'

Categories