Import dynamic file with require React - javascript

Hello there I'm importing a dynamic file with require, but my file is outside of /src so I check a post that say if I comment two lines in ./node_modules/react-scripts/config/webpack-config.js
I can access to files outside of /src, the problem is that if I do this works fine:
Show PDF
but if i want to be dynamic receiving the path through props i get this error:
Error: Cannot find module '../../../../../files/asd.pdf'
Where my code is this and this.state.fullPath is the same of before.
Show PDF
I try concatenating a empty string but still not working

This is a problem that relates to the module bundler that you are using. In order for it to work, the require function has to get a path which the bundler will use to import the module at build time rather than runtime. You will need to use require using the full path and not a variable.
You can try something like:
const one = require('./path/to/one.pdf');
const two = require('./path/to/two.pdf');
const href = variable === 1 ? one : two;
Show PDF

Related

How to tune babel loader to properly import a module named macro.js when using CRA

I'm using a library vtk.js. VTK has a special design of classes (https://kitware.github.io/vtk-js/docs/develop_class.html). When I write a class I need to import macro.js module which exposes several base methods such as getters/setters/newInstance etc (https://github.com/Kitware/vtk-js/blob/master/Sources/macro.js).
Looks like CRA uses some special loader for macro.js files. I get an error when trying to import such a file (SyntaxError: Cannot use import statement outside a module). If I copy an original file macro.js from #kitware/vtk.js to my local source folder I still get an error. Even if I remove all the contents of macro.js file I get an error (The macro imported from "../macro" must be wrapped in "createMacro" which you can get from "babel-plugin-macros". Please refer to the documentation to see how to do this properly: https://github.com/kentcdodds/babel-plugin-macros/blob/master/other/docs/author.md#writing-a-macro). However, when I rename macro.js to macro2.js the error is gone.
Is there some way how can I disable this macro loader?

How to import html file into react as string?

I have an HTML template as a separate file that I would like to import into my react application. The intention will be replacing specific keywords and then sending it as the body in an email.
How can I import this html file into my react application?
I have tried import htmlString from '../../../constants/EmailHTML.html'; as well as var html = require('../../../constants/EmailHTML.html'); (which was suggested in this similar question)
I get the following error for both attempts:
Module parse failed: Unexpected token (1:0) You may need an
appropriate loader to handle this file type, currently no loaders are
configured to process this file.
Effectively this question boils down to: How do I import a text file as a string in React? This is an often-answered question and all the results seem to be to use an async loader -- something that shouldn't really need to happen given the file is in my src directory ready to go before build.
Answer for create-react-app:
Install the raw-loader package npm i --save raw-loader
Add a test HTML file you want read to src. I added test.html.
Add the lines below where you want to get the contents of the HTML file into a JavaScript string. html will contain the string contents of the file.
Code:
// eslint-disable-next-line import/no-webpack-loader-syntax
var htmlModule = require('raw-loader!./test.html');
var html = htmlModule.default;

Import JSON file in NodeJs using es6

Hi i'm currently learning nodejs and I try to import a json file like this :
'use strict'
import data from 'users.json'
console.log(data)
Each time I get this error "Cannot find package 'users.json'"
But if I read the file with fs it worked so can you explain me how to do please
try :
import data from './users'
which is the es6 method of doing things or if you want an older syntax method you can try
const data = require('./users')
Okay so the explanation just is this, those fullstops and forward slash are used to indicate relative paths to the file the import is being called from, which means somethings you'd see something like for example ../file/help. The ./ means go up one directory ../ means go up two directories and so on. The name after the slash just tells your program the folder to go in to look for the file to import from so ./folder means go up one directory and enter into the folder directory and so on.
Almost forgot to mention, you should not import from a json file or a text file or any other file that does not have a .js extention(of which you do not actually have to specify) unless absolutely neccessary. To deal with files in node you have to use the fs library.
const fs =require('fs')
....
fs.readFile('./users.json','utf-8',(err,jsonString)=>{
const data = JSON.parse(jsonString);
//whatever other code you may fanacy
}
take a look at the fs module for a list of awesome features you can use to play with files
While the selected answer is correct, here's an explanation that I hope might add some clarity:
import MyModule from 'some-module'
is ES6 import syntax, as opposed to the older CommonJS syntax, which uses require.
CommonJS's require can be used to import files generally; ES6's import statement is more specific, and is generally used for importing js files which meet the criteria for being a module (having an export statement), or specific assets such as CSS sheets. Unlike require, it won't generally work for reading in files that are not modules.
You can't mix CommonJS require and ES6 import in the same file (at least not easily), so if you're using ES6 import and wish to read a file, do so with fs.readFileSync or a similar method. If the file is a json string, you'll need to parse it with JSON.parse().
If you want to use ES6 (NOT CommonJS) module system but want to use the Node.js version which is less than V18 (supports direct json import) then use the below approach.
import { createRequire } from "module";
const require = createRequire(import.meta.url); // construct the require method
const data = require("users.json"); // Now you can use require method in ES6
console.log(data)

I'd like to reuse code from another module in my Nodejs backend

I'm using the Yeoman Generator Angular Fullstack and I'd like to reuse JS code from different directories within my server directory. I'm referencing the file that has the functions I want like:
var something = require('/.path');
I get the error: "Cannot find module" in my terminal.
I tried a number of variations of the path working through all of the levels from server level down to file level where the given functions are contained. I looked at a few tutorials:
http://www.sitepoint.com/understanding-module-exports-exports-node-js/
AND
https://www.launchacademy.com/codecabulary/learn-javascript/node/modules
I clearly missed something. Each module of my nodejs has a controller with an exports.create function. All of my code for each module is contained within my exports.create function accept for other required modules. I have no problem requiring underscore or other libraries in my Node/Bower modules by the way.
To be as detailed as can be, I expected
var something = require('./directory/directory.controller.js');
var something = require('/.path');
The path you are using is likely incorrect. Probably you want to open the file called path.js contained in the same folder of the file from which you are importing it. In order to do that, you should change the import as follows :
var something = require('./path');
./path is a relative path where . stands for current directory.
/.path is an absolute path. In this case require is importing a hidden file in the root directory. I guess is not what you want.

Including Javascript Library in Node Express Routes

I'm trying to use the Sanford encryption library(sjcl) in my Express App.
I've tried to the following in my app.js file:
var sjcl = require('.lib/sjcl.js');
Next I try to call sjcl.encrypt in my routes/journal.js file, but get an error that it's not defined.
Next I tried requiring the the library in my journal.js file at the beginning, but get the module ./lib/sjcl.js cannot be found.
The sjcl.js library does export the sjcl object so that doesn't seem to be it.
Any ideas on how I can gain access to the sjcl library from within my routers file?
Next I try to call sjcl.encrypt in my routes/journal.js file, but get an error that it's not defined.
require() just returns an object representing that module.
var x = require(...) assigns that object to a local variable.
It doesn't affect other .js files.
Next I tried requiring the the library in my journal.js file at the beginning, but get the module ./lib/sjcl.js cannot be found.
That would happen if your relative path is wrong.

Categories

Resources