Using relative paths with react-native - javascript

I am trying to import Module using relative path in react-native , my project structure is like this :
-Project
--Components
--- adapter.js
--src
---screen
----Main.js
--App.js
I want to use adapter.js in my Main.js , so in the Main.js i use : import adapter from '/../Components/adapter'
this will throw the following error :
Module not found: Can't resolve '/../Components/adapter' in
'E:\reactjs\learn\Project\src\screens'

You can use https://github.com/tleunen/babel-plugin-module-resolver, it's a good module to have alias with import.
You have to specify a babel.config.js in React Native and a configuration:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
'module-resolver',
{
root: ['./src'],
alias: {
components: './src/components',
_main: './src/components/_main',
screens: './src/screens',
config: './src/config',
navigations: './src/navigations',
utils: './src/utils',
actions: './src/state/actions',
constants: './src/state/constants',
contexts: './src/state/contexts',
reducers: './src/state/reducers',
assets: './src/assets/',
hooks: './src/hooks',
data: './src/data',
},
},
],
],
};
And after, you can import your module like this :
import HomeFeed from 'components/Home';

Note: that VSCode will detect the import
You need to add a tsconfig.js file
The next line
"baseUrl": "src"

Since your file Main.js is inside src/screen and adapter.js is inside Components, you need to go two levels down from Main.js to get out of screen, src and then enter Components.
You will end up with something like ../../Components/adapter.

Related

Why is the file `vite.svg` in the `dist` folder when building with Vite library mode?

I am trying to publish a React component as an npm module using the library mode of Vite. But even though my entry file does not import or use the image vite.svg it is copied to the dist folder.
vite.config.js:
export default defineConfig({
plugins: [react()],
build: {
lib: {
// Could also be a dictionary or array of multiple entry points
entry: resolve(__dirname, 'src/index.jsx'),
name: 'MyLib',
// the proper extensions will be added
fileName: 'my-lib',
},
rollupOptions: {
// make sure to externalize deps that shouldn't be bundled
// into your library
external: ['react', 'react-dom'],
output: {
// Provide global variables to use in the UMD build
// for externalized deps
globals: {
react: 'React',
'react-dom': 'ReactDOM',
},
},
},
},
})
src/index.jsx:
import React from 'react';
export function Button(props) {
return <button {...props} />;
}
dist
📂dist
┣ 📜my-lib.js
┣ 📜my-lib.umd.cjs
┗ 📜vite.svg
By default, Vite will automatically copy all files inside publicDir into the outDir when building. The default value of publicDir is public and this folder (with the file vite.svg) is created when starting a new project with npm create vite.
The easiest way to get rid of this file is to just delete the public folder.
There is also an option copyPublicDir that can be set to false in order to disable this behavior and not copy any files from the set publicDir to outDir.

Vite+Vue - Package referenced via npm link can't resolve vite.resolve.alias

I'm developing a package to help other developers here in our company.
I know that I can create aliases to make the code more cleaner and help the readability of it.
So:
PACKAGE PROJECT
vite.config.js
import { defineConfig } from 'vite'
import path from 'path'
export default defineConfig({
resolve:{
preserveSymlinks: false,
alias:{
'#' : path.resolve(__dirname, 'src'),
},
// ....
})
Assume that I've the following folder structure
src
helpers
commonHelper.js
index.js
src/index.js
import {merge} from '#/helpers/commonHelper.js'
export {merge}
PROJECT THAT REFERENCES PACKAGE PROJECT
vite.config.js
It alsos have a vite.config.js with an # alias pointing to it self src
import { defineConfig } from 'vite'
import path from 'path'
export default defineConfig({
resolve:{
preserveSymlinks: false,
alias:{
'#' : path.resolve(__dirname, 'src'),
},
// ....
})
anyfile.js
Lets assume that my package project is called foo and it's referenced using npm link for testing now, after finishing the package it will be referenced using npm install
import {merge} from 'foo'
merge({},{});
When i try to run my project i got the following error
[vite] Internal server error: Failed to resolve import "#/helpers/commonHelper.js" from
"..\..\npmPackages\foo\src\index.js". Does the file exist?
Plugin: vite:import-analysis
File: E:/_Development/foo/src/index.js
3 | import {merge} from '#/helpers/commonHelper.js'
| ^
4 | export {merge}
at formatError (file:///E:/_Development/project/node_modules/vite/dist/node/chunks/dep-557f29e6.js:40853:46)
at TransformContext.error (file:///E:/_Development/project/node_modules/vite/dist/node/chunks/dep-557f29e6.js:40849:19)
at normalizeUrl (file:///E:/_Development/project/node_modules/vite/dist/node/chunks/dep-557f29e6.js:37586:33)
at async TransformContext.transform (file:///E:/_Development/project/node_modules/vite/dist/node/chunks/dep-557f29e6.js:37719:47)
at async Object.transform (file:///E:/_Development/project/node_modules/vite/dist/node/chunks/dep-557f29e6.js:41102:30)
at async loadAndTransform (file:///E:/_Development/project/node_modules/vite/dist/node/chunks/dep-557f29e6.js:37364:29)
As far i noticed the problem is happening because # is pointing to the project that references the foo package
What can i do?
I assume that you're using Vite to build the lib.
In that case using "npm link" or the publishing process, you should point in your package.json of the package using the field "module" to the generated ESM library file instead of the actual source code.
Then you can use the package in your other project same as if it was installed from some package registry.
Please do not use '/src', use '#/' instead

how to use a library of Vue3 components as standalone Web Components?

I have a set of Vue3 components in a Vite architecture and want to publish them as a lib of pure web components. how can i use my built files to do so ?
I followed the Vite docs to build a lib. It says to add this in the vite.config.js file:
const path = require('path');
const {defineConfig} = require('vite');
const vue = require('#vitejs/plugin-vue');
// https://vitejs.dev/config/
export default defineConfig({
build: {
lib: {
entry: path.resolve(__dirname, 'src/components/index.js'),
name: 'TykaynLib',
fileName: (format) => `tykayn-lib.${format}.js`,
},
rollupOptions: {
external: ['vue'],
output: {
// Provide global variables to use in the UMD build
// Add external deps here
globals: {
vue: 'Vue',
TykaynLib : 'TykaynLib'
},
},
},
},
plugins: [vue()],
});
So after the build i get ES and UMD files containing my components, but they are not standalone, they require VueJS to be able to work.
I wanted pure web components that i could use by just loading a script and having to just add my custom HTML tags inside an HTML file. I do NOT want to make a plugin for vue or require the end users of my components to have to use Vue.
Is there a way to build this ?

NextJS styled-components giving an error in bundle file

I am using styled-components for my React project. After I bundled my react application with rollupjs then I am trying to use this bundle with NextJS. It is getting error in NextJS:
ReferenceError: window is not defined
When I look line of error in the bundle file this error is happening inside of styled-components.
Here is my rollup.config.js in React App (not Nextjs):
import babel from "rollup-plugin-babel";
import commonjs from "#rollup/plugin-commonjs";
import external from "rollup-plugin-peer-deps-external";
import postcss from "rollup-plugin-postcss";
import resolve from "#rollup/plugin-node-resolve";
import image from "#rollup/plugin-image";
import visualizer from "rollup-plugin-visualizer";
import pkg from "./package.json";
// PostCSS plugins
import simplevars from "postcss-simple-vars";
import nested from "postcss-nested";
import cssnext from "postcss-cssnext";
import cssnano from "cssnano";
import cssvariables from "postcss-css-variables";
const extensions = [".js", ".jsx", ".ts", ".tsx"];
export default {
input: ["./src/index.js"],
output: [
{
file: pkg.main,
format: "cjs",
globals: { react: "React" },
},
{
file: pkg.module,
format: "esm",
},
],
plugins: [
external(["react", "uikit"]),
postcss({
plugins: [
simplevars(),
cssvariables(),
nested(),
cssnext({ warnForDuplicates: false }),
cssnano(),
],
extensions: [".css"],
}),
babel({
exclude: "node_modules/**",
extensions,
}),
// Allows node_modules resolution
resolve({
mainFields: ["module", "main", "jsnext:main", "browser"],
dedupe: ["react", "react-dom"], // Default: []
extensions,
}),
commonjs(),
image(),
visualizer(),
],
};
How can I solve this error in NextJS with bundle code?
Thanks
It means your window related code is executed on the Node.js side, not on the browser. Since Next.js is server-side rendering framework, you should make sure that you don't use browser thing (like window object) in the code that is executed on the server side.
Please reference this article.
UPDATE
Please check your .babelrc -
{
"presets": ["next/babel"],
"plugins": [["styled-components", { "ssr": true }]]
}

How do we include only required modules from lodash in a Nuxt?Vuejs Project?

We have built a Nuxt/VueJS project.
Nuxt has its own config file called nuxt.config.js within which we configure webpack and other build setup.
In our package.json, we have included the lodash package.
In our code, we have been careful to load only import what we require, for example:
import orderBy from 'lodash/orderBy'
In nuxt.config.js, lodash is add to the vendor list.
However when we create the build, webpack always includes the entire lodash library instead of including only what we have used in our code.
I have read numerous tutorials but haven't got the answer. Some of those answers will surely work if it was a webpack only project. But in our case, it is through nuxt config file.
Looking forward to some help.
Below is the partial nuxt.config.js file. Only relevant/important parts are included:
const resolve = require('resolve')
const webpack = require('webpack')
module.exports = {
/*
** Headers of the page
*/
head: {
},
modules: [
['#nuxtjs/component-cache', { maxAge: 1000 * 60 * 10 }]
],
plugins: [
{ src: '~/plugins/intersection', ssr: false },
],
build: {
vendor: ['moment', 'lodash'],
analyze: {
analyzerMode: 'static'
},
postcss: {
plugins: {
'postcss-custom-properties': false
}
},
plugins: [
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
],
/*
** Run ESLINT on save
*/
extend (config, ctx) {
// config.resolve.alias['create-api'] = `./create-api-${ctx.isClient ? 'client' : 'server'}.js`
}
}
}
You can npm install only the required packages
Lodash can be split up per custom builds. You can find a list of already available ones here. You can use them like this: npm i -S lodash.orderby. I didn't check it but you would probably also need to change import orderBy from 'lodash/orderBy' to import orderBy from 'lodash.orderby'.

Categories