Importing functions from other files not working (React) - reactjs

Import:
import { get, set, faviconChange } from '/js/title.js';
title.js
var geta = a => localStorage.getItem(a)
var seta = (a, b) => localStorage.setItem(a, b)
export function get(a) {
localStorage.getItem(a);
}
export function set(a,b) {
localStorage.setItem(a,b);
}
document.title = get('title') || 'Anonymous'
var link = document.createElement('link');
link.rel = 'icon';
document.getElementsByTagName('head')[0].appendChild(link);
export function faviconChange(value) {
set('link', value)
link.href = get('link') || '/favicon.ico';
console.log("working " + link.href)
}
link.href = get('link') || '/favicon.ico';
Error:
./pages/index.js:6:0
Module not found: Can't resolve '/js/title.js'
4 | import Particles from 'react-tsparticles';
5 | import { loadFull } from "tsparticles";
> 6 | import { get, set, faviconChange } from '/js/title.js';
7 |
8 |
9 | export default function Home() {
https://nextjs.org/docs/messages/module-not-found
Whenever I try and import these functions, I get the above error and I've looked it up, and everyone seems to do it this way, yet I get an error. Am I missing something/putting these imports in the wrong file?

Try to import from './js/title.js';
When importing from another file, you must go up in the files hierarchy with a dot './'

3 suggestions are here.
1. adding export in your importing file
export default YourFunctionName;
2. As #SaF mentioned, make sure the path is correct
How?
If you are using linux/unix/mac use the command tree on the parent folder to get the exact path (if windows, you can install tree)
try using ../../../folder_x to go to folder_x which is 3 folders behind and ./ to get current folder
try printing your js file's absolute path using fs module https://www.npmjs.com/package/fs-js (comment the import line and try this)
3. Change jsx file extention to normal js
and add below code in webpack.config.js to resolve jsx as js
module.exports = {
//...
resolve: {
extensions: ['.js', '.jsx']
}
};

Related

Error: Zxing functions does not exists. React QR Scanning App

I am trying add a qr code scanning functionality to my react app. I am using #zxing(https://www.npmjs.com/package/#zxing/browser & https://www.npmjs.com/package/#zxing/library) packages.
Following the readme, here's my js code. I have hosted the application on aws so its SSL covered. But I can't seem to figure out the issue. I have read the git repo of both and the functions do exists(https://github.com/zxing-js/browser/tree/master/src/readers)
import React, { useState, useEffect } from "react";
import {
NotFoundException,
ChecksumException,
FormatException
} from "#zxing/library";
import { BrowserQRCodeReader, BrowserCodeReader } from '#zxing/browser';
export default function() {
var qrCodeReader = null;
var codeReader = null;
var sourceSelect = null;
console.log("ZXing code reader initialized");
useEffect(() => {
codeReader = new BrowserCodeReader();
qrCodeReader = new BrowserQRCodeReader();
console.log(codeReader.listVideoInputDevices()); // ISSUE: RETURNS -> listVideoInputDevices() is not a fuction
console.log(qrCodeReader.listVideoInputDevices()); // ISSUE: RETURNS -> listVideoInputDevices() is not a fuction
console.log("Code Reader", codeReader); // ISSUE: SEE IMAGE BELOW
console.log("QR Code Reader", qrCodeReader); // ISSUE: SEE IMAGE BELOW
}, []);
Instead of using the import try using:
`
const zxing = require('zxing-js/library');
`

Serve static javascript file from nextjs api

I need a route in website build with nextjs that sends javascript that can be used on different website to do some things.
I created new file in pages/api, let's call it sendTest.ts so it's location is pages/api/sendTest.ts. In the same folder I crated test.ts file that I want to send from sendTest.ts.
sendTest.ts
import type { NextApiRequest, NextApiResponse } from 'next'
import fs from 'fs';
import path from 'path'
const filePath = path.join(__dirname, 'test.js');
const file = fs.readFileSync(filePath);
export default function handler(
req: NextApiRequest,
res: NextApiResponse
) {
res.setHeader('Content-Type', 'text/javascript');
res.status(200).send(file)
}
test.ts
console.log('hello');
After build nextjs serves that file at website.com/api/sendTest but after bundling it ends up as
"use strict";
(() => {
var exports = {};
exports.id = 318;
exports.ids = [318];
exports.modules = {
/***/ 211:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
console.log("hello there");
/***/ })
};
;
// load runtime
var __webpack_require__ = require("../../webpack-api-runtime.js");
__webpack_require__.C(exports);
var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))
var __webpack_exports__ = (__webpack_exec__(211));
module.exports = __webpack_exports__;
})();
which when used in different page as
<script src="website.com/api/sendTest"></script>
results in error
Uncaught ReferenceError: require is not defined
at sendTest:22:27
at sendTest:28:3
My question is how can I force nextjs to skip loading webpack into that file and just allow typescript to change content into javascript and serve file as is? Or is there better way to do what I want, which is sending javascript from specified nextjs route?
Got it.
I changed
const filePath = path.join(__dirname, 'test.js');
to
const filePath = path.resolve('.', 'script/test.js');
and put my script file into folder called script (name doesn't matter) in the main directory

How to conditionally import file in Reactjs

I have have a large application that monitors a file called routes.js . I can not change the file name or mess with routes.js at all. I need to load another file based on a useState variable from another component when a condition is met. This following code will need to be put in Apps.js example:
if (!change) {
import routes from "routes";
} else {
import routes from "newroutes"
}
Is this possible?
You can just alias the imports.
import routes_1 from "routes";
import routes_2 from "newroutes"
Then, you can just declare a variable: routes and assign the appropriate value to it.
routes = !change ? routes_1 : routes_2;
It's possible to do using Webpack lazy loading (if you build your app using Webpack):
import(/* webpackChunkName: "routes" */ './routes').then(module => {
const routes = module.default;
});
But probably you will need to adjust your build config. Also this import is returning a promise, so you should write your code in the callback.
Update: but in your case it seems you don't need it. You could do something like this:
import file1 from 'routes'
import file2 from 'newroutes'
let routes = file1
if (change) {
routes = file2
}
So you will have your routes variable unchanged

How use method isEqual in react

I use the method _.isEqual in my function:
const Sidebar = ({ ...props }) => {
function myFunction(codeMenu) {
let menu = null;
const listMenu = props.listMenu;
for(var i = 0; i < listMenu.length; i++){
if(_.isEqual(listMenu[i].code, codeMenu)){
menu = listMenu[i];
}
break;
}
}
}
...
But I have this error:
'_' is not defined no-undef
loadsh is imported in my index.html :
https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js
Instead of using lodash via cdn, use it via npm. Please run following commands:
npm install lodash
and then import it in the file like
import _ from 'lodash';
and then use it. Actually more optimal way to import is:
import isEqual from 'lodash/isEqual';
so that extra lodash package might not be included in the bundle
One reason you may getting that error is that your React bundle is executed before lodash. In that case _ would not have been added to the global scope.
To avoid these kind of issues, I suggest ditching the CDN and instead add lodash as a dependency to your package.json file. You can then cosume lodash as a require or import.
If you import isEqual as import isEqual from 'lodash/isequal' and you're using a bundler such as Webpack, it will not bundle the other lodash functions you're not importing, dramatically reducing the amount of code your browser has to download.
Seems like your _ object is not defined. Did you import lodash like var _ = require('lodash'); ?
You need to import lodash using npm install command
Here's full code how ->
import lodash from lodash
// Load the full build.
var _ = require('lodash');
// Load the core build.
var _ = require('lodash/core');
const Sidebar = ({ ...props }) => {
function myFunction(codeMenu){
let menu = null;
const listMenu = props.listMenu;
for(var i = 0; i < listMenu.length; i++){
if(_.isEqual(listMenu[i].code, codeMenu)){
menu = listMenu[i];
}
break;
}
}

react native (expo) load markdown files

I'm having some troubles loading markdown files (.md) into my react native (non-detached expo project).
Found this awesome package that allows me to render it. But can't figure out how to load the local .md file as a string.
import react from 'react';
import {PureComponent} from 'react-native';
import Markdown from 'react-native-markdown-renderer';
const copy = `# h1 Heading 8-)
| Option | Description |
| ------ | ----------- |
| data | path to data files to supply the data that will be passed into templates. |
| engine | engine to be used for processing templates. Handlebars is the default. |
| ext | extension to be used for dest files. |
`;
export default class Page extends PureComponent {
static propTypes = {};
static defaultProps = {};
render() {
return (
<Markdown>{copy}</Markdown>
);
}
}
BTW: I tried googling, but can't get the suggestions to work
https://forums.expo.io/t/loading-non-media-assets-markdown/522/2?u=norfeldtconsulting
I tried the suggested answers for reactjs on SO, but the problem seems to be that it only accepts .js and .json files
Thanks to #Filipe's response, I got some guidance and got a working example that will fit your needs.
In my case, I had a .md file on the assets/markdown/ folder, the file is called test-1.md
The trick is to get a local url for the file, and then use the fetch API to get its content as a string.
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Markdown from 'react-native-markdown-renderer';
const copy = `# h1 Heading 8-)
| Option | Description |
| ------ | ----------- |
| data | path to data files to supply the data that will be passed into templates. |
| engine | engine to be used for processing templates. Handlebars is the default. |
| ext | extension to be used for dest files. |
`;
export default class App extends React.Component {
constructor(props) {
super(props)
this.state = {
copy: copy
}
}
componentDidMount() {
this.fetchLocalFile();
}
fetchLocalFile = async () => {
let file = Expo.Asset.fromModule(require("./assets/markdown/test-1.md"))
await file.downloadAsync() // Optional, saves file into cache
file = await fetch(file.uri)
file = await file.text()
this.setState({copy: file});
}
render() {
return (
<Markdown>{this.state.copy}</Markdown>
);
}
}
EDIT: In order to get get rid of the error
Unable to resolve "./assets/markdown/test-1.md" from "App.js"
you would need to add the packagerOpts part of #Filipe's snippet into your app.json file.
app.json
{
"expo": {
...
"assetBundlePatterns": [
"**/*"
],
"packagerOpts": {
"assetExts": ["md"]
},
...
}
}
EDIT 2:
Answering to #Norfeldt's comment:
Although I use react-native init when working on my own projects, and I'm therefore not very familiar with Expo, I got this Expo Snack that might have some answers for you: https://snack.expo.io/Hk8Ghxoqm.
It won't work on the expo snack because of the issues reading non-JSON files, but you can test it locally if you wish.
Using file.downloadAsync() will prevent the app making XHR calls to a server where your file is hosted within that app session (as long as the user does not close and re-open the app).
If you change the file or modify the file (simulated with a call to Expo.FileSystem.writeAsStringAsync()), it should display the updated as long as your component re-renders and re-downloads the file.
This will happen every time your app is closed and re-open, as the file.localUri is not persisted per sessions as far as I'm concerned, so your app will always call file.downloadAsync() at least once every time it's opened. So you should have no problems displaying an updated file.
I also took some time to test the speed of using fetch versus using Expo.FileSystem.readAsStringAsync(), and they were on average the same. Often times Expo.FileSystem.readAsStringAsync was ~200 ms faster, but it 's not a deal breaker in my opinion.
I created three different methods for fetching the same file.
export default class MarkdownRenderer extends React.Component {
constructor(props) {
super(props)
this.state = {
copy: ""
}
}
componentDidMount() {
this.fetch()
}
fetch = () => {
if (this.state.copy) {
// Clear current state, then refetch data
this.setState({copy: ""}, this.fetch)
return;
}
let asset = Expo.Asset.fromModule(md)
const id = Math.floor(Math.random() * 100) % 40;
console.log(`[${id}] Started fetching data`, asset.localUri)
let start = new Date(), end;
const save = (res) => {
this.setState({copy: res})
let end = new Date();
console.info(`[${id}] Completed fetching data in ${(end - start) / 1000} seconds`)
}
// Using Expo.FileSystem.readAsStringAsync.
// Makes it a single asynchronous call, but must always use localUri
// Therefore, downloadAsync is required
let method1 = () => {
if (!asset.localUri) {
asset.downloadAsync().then(()=>{
Expo.FileSystem.readAsStringAsync(asset.localUri).then(save)
})
} else {
Expo.FileSystem.readAsStringAsync(asset.localUri).then(save)
}
}
// Use fetch ensuring the usage of a localUri
let method2 = () => {
if (!asset.localUri) {
asset.downloadAsync().then(()=>{
fetch(asset.localUri).then(res => res.text()).then(save)
})
} else {
fetch(asset.localUri).then(res => res.text()).then(save)
}
}
// Use fetch but using `asset.uri` (not the local file)
let method3 = () => {
fetch(asset.uri).then(res => res.text()).then(save)
}
// method1()
// method2()
method3()
}
changeText = () => {
let asset = Expo.Asset.fromModule(md)
Expo.FileSystem.writeAsStringAsync(asset.localUri, "Hello World");
}
render() {
return (
<ScrollView style={{maxHeight: "90%"}}>
<Button onPress={this.fetch} title="Refetch"/>
<Button onPress={this.changeText} title="Change Text"/>
<Markdown>{this.state.copy}</Markdown>
</ScrollView>
);
}
}
Just alternate between the three to see the difference in the logs.
From what I know, this cannot be done within expo. I use react-native and run it on my mobile for development.
react-native use Metro as the default bundler, which also suffers from similar problems. You have to use haul bundler instead.
npm install --save-dev haul
npx haul init
npx haul start --platform android
In a seperate terminal run react-native run-android. This would use haul instead of metro to bundle the files.
To add the markdown file, install raw-loader and edit the haul.config.js file. raw-loader imports any file as a string.
Customise your haul.config.js to look something like this:
import { createWebpackConfig } from "haul";
export default {
webpack: env => {
const config = createWebpackConfig({
entry: './index.js',
})(env);
config.module.rules.push({
test: /\.md$/,
use: 'raw-loader'
})
return config;
}
};
Now you can import the markdown file by using const example = require('./example.md')
Haul supports webpack configuration so you can add any custom babel transform you want.
I don't know exactly where the problem lies, but I added html files to the project, and I'd imagine it would be very similar.
Inside your app.json, try adding these fields:
"assetBundlePatterns": [
"assets/**",
],
"packagerOpts": {
"assetExts": ["md"]
},
The packagerOpts makes it so the standalone will bundle the .md files. I'd imagine you already have an assets folder, but just in case you don't, you will need one.
Then, on AppLoading, loading the assets with Asset.loadAsync might not be needed, but it's a good idea to rule out. Check out the documentation on how to use it.
When importing the file, there are three ways you might want to do so, that change depending on the environment. I'll copy this excerpt from my Medium article:
In the simulator, you can access any file in the project. Thus, source={require(./pathToFile.html)} works. However, when you build a standalone, it doesn’t work quite in the same way. I mean, at least for android it doesn’t. The android webView doesn’t recognise asset:/// uris for some reason. You have to get the file:/// path. Thankfully, that is very easy. The assets are bundled inside file:///android_asset (Careful, don’t write assets), and Expo.Asset.fromModule(require(‘./pathToFile.html')).localUri returns asset:///nameOfFile.html. But that’s not all. For the first few times, this uri will be correct. However, after a while, it changes into another file scheme, and can’t be accessed in the same way. Instead, you’ll have to access the localUri directly. Thus, the complete solution is:
/* Outside of return */
const { localUri } = Expo.Asset.fromModule(require('./pathToFile.html'));
/* On the webView */
source={
Platform.OS === ‘android’
? {
uri: localUri.includes('ExponentAsset')
? localUri
: ‘file:///android_asset/’ + localUri.substr(9),
}
: require(‘./pathToFile.html’)
}
(A constant part of the uri is ExponentAsset, that’s why I chose to check if that was part of it)
That should probably solve your problem. If it doesn't, comment what's going wrong and I'll try to help you further. Cheers!
If you want to load .md file with react-native cli (without expo). I've got a solution for you)
Add https://github.com/feats/babel-plugin-inline-import to your project
Add config .babelrc file with code inside:
{
"presets": ["module:metro-react-native-babel-preset"],
"plugins": [
[
"inline-import",
{
"extensions": [".md", ".txt"]
}
],
[
"module-resolver",
{
"root": ["./src"],
"alias": {}
}
]
]
}
Add to your metro.config.js such code
const metroDefault = require('metro-config/src/defaults/defaults.js');
...
resolver: {
sourceExts: metroDefault.sourceExts.concat(['md', 'txt']),
}
....
Reload your app

Resources