Javascript: Problem of javascript file import in yarn build - javascript

I have two JavaScript codes.
I would like to import and use another one from one javaScript code.
I tried a few things to import, but there was an error.
This is my main code(main.js):
import * as test from "./noise";
const audioContext = new AudioContext({sampleRate: 48000});
const destination = audioContext.createMediaStreamDestination();
await NoiseNode.register(audioContext)
And, This is the code that I want to import(noise.js):
window.NoiseNode = (window.AudioWorkletNode || (window.AudioWorkletNode = window.webkitAudioWorkletNode)) &&
class extends AudioWorkletNode {
static async register(a) {
k = await h;
await a.audioWorklet.addModule(g + "other.js");
}}
If i try to import as below,
import * as test from "./noise;
These errors occur:
Line 141:15: 'NoiseNode' is not defined no-undef
and then, If i try to import as below,
import * as NoiseNode from "./noise";
These errors occur:
Attempted import error: 'register' is not exported from './noise' (imported as 'NoiseNode').
How can I get everything at once?
Please give me some advice.
Thank you.

You have to export NoiseNode before importing it.
export window.NoiseNode = (window.AudioWorkletNode || (window.AudioWorkletNode = window.webkitAudioWorkletNode)) &&
after exporting, you may import it using the following code:
import * as NoiseNode from "./noise";

Related

How to use an existing JS file in a vue project

I need to use this JS file in my vue3 project.
https://gist.github.com/imolorhe/b31f95e1548ad7d1b233de26267fe21c#file-jungle-js
My JS library is
import { Jungle } from "./jungle.js";
async pitchTransform(
audioBuffer,
pitchMod
) {
let ctx = new OfflineAudioContext(
audioBuffer.numberOfChannels,
audioBuffer.length,
audioBuffer.sampleRate
);
let source = ctx.createBufferSource();
source.buffer = audioBuffer;
let pitchChangeEffect = new Jungle(ctx);
}
The application shows this error:
Uncaught SyntaxError: The requested module '/src/js/jungle.js?t=1659194585032' does not provide an export named 'Jungle' (at voiceTransform.js?t=1659199164108:1:10)
What's the recommend way to include and use jungle.js in this setup?
As the error is saying, that file has no export named "Jungle". In fact it has none.
You have to export that function manually, by editing that file and appending an export keyword:
// ...
export function Jungle(context) {
// ...

How do I resolve the error I have in my JavaScript using imports?

I'm attempting to import a function from 2 different files into another one of my JavaScript files, but in the file that's importing the functions, I'm getting the error that each function is declared, but never read.
capital.js file:
function capital(string) {
const capitalizedString =
string.substring(0, 1).toUpperCase() + string.substring(1);
return capitalizedString;
}
alert(capital("Jon"));
export default capital;
addDOMContent.js file:
function addDOMContent(content) {
const node = document.createElement("h1");
node.innerText = content;
document.body.appendChild(node);
}
addDOMContent("Success!");
export default addDOMContent;
index.js file:
import capital from "./capital.js";
import addDOMContent from "./addDOMContent.js";
Why aren't my files being properly imported?

Dynamically import and render an SVG image with React?

I'm trying to dynamically render SVG images from the react-icons SVG library.
This is a component that is to be rendered multiple times on the page each with a different passed string referencing an SVG filename in the react-icons library.
I'd like to import and render the SVG file based on the matching filename string for each SVG which is located in averageWeather.weather[0].icon.
averageWeather.weather[0].icon === 'svgFileName'
I need to:
Find a way of importing the entire WI library in a way that I can extract a single file with the string in averageWeather.weather[0].icon.
Redner that extracted file in JSX.
I could import all of my required images individually like so:
import { SVGimg1, SVGimg2, SVGimg3, SVGimg4, etc, etc } from 'react-icons/wi'
But surely there's a better way than this? I'd rather not do this as I need to access many possible images which will undoubtedly grow in the future.
My best attempt at the moment:
import React from 'react'
import * as classes from './WeatherIcon.module.scss'
import { findMostFrequent } from '../../../shared/weather'
import * as SVG from 'react-icons/wi'
const WeatherIcon = props => {
const averageWeather = findMostFrequent(props.list)
return (
<div className={classes.WeatherIcon}>
<SVG.{averageWeather.weather[0].icon} />
</div>
)
}
export default WeatherIcon
findMostFrequent(props.list) returns an object containing the filename I need.
This is what I wish to be possible:
import React from 'react'
import * as classes from './WeatherIcon.module.scss'
import { findMostFrequent } from '../../../shared/weather'
const WeatherIcon = props => {
const averageWeather = findMostFrequent(props.list)
const {averageWeather.weather[0].icon} = require('react-icons/wi')
return (
<div className={classes.WeatherIcon}>
<{averageWeather.weather[0].icon}/>
</div>
)
}
export default WeatherIcon
I have tried const reqSvgs = require.context('react-icons/wi', true, /\.svg$/).
I get this error when I try this:
webpackEmptyContext(req) {
var e = new Error("Cannot find module '" + req + "'");
e.code = 'MODULE_NOT_FOUND';
throw e;
}
Is this possible?

How to use a static javascript function from another javascript file?

Hello and thank you for your time.
I am trying to make a JavaScript example application working.
The fact is I do not know exactly how to use this static function:
core.utils.js
static parseUrl(url) {
const data = {};
data.filename = '';
data.extension = '';
data.pathname = '';
data.query = '';
let parsedUrl = URL.parse(url);
data.pathname = parsedUrl.pathname;
data.query = parsedUrl.query;
if (data.query) {
// Find "filename" parameter value, if present
data.filename = data.query.split('&').reduce((acc, fieldval) => {
let fvPair = fieldval.split('=');
if (fvPair.length > 0 && fvPair[0] == 'filename') {
acc = fvPair[1];
}
return acc;
});
}
// get file name
if (!data.filename) {
data.filename = data.pathname.split('/').pop();
}
// find extension
let splittedName = data.filename.split('.');
if (splittedName.length <= 1) {
data.extension = 'dicom';
} else {
data.extension = data.filename.split('.').pop();
}
if (!isNaN(data.extension)) {
data.extension = 'dicom';
}
if (data.query &&
data.query.includes('contentType=application%2Fdicom')) {
data.extension = 'dicom';
}
return data;
}
Into the javascript file which has the appliaciton's logic.
I have tried the direct import used by the IDE itself, webstorm in my case:
import CoreUtils from "../../src/core/core.utils";
However, the browser's console says:
Uncaught SyntaxError: Unexpected identifier
And the line where is the error is:
import CoreUtils from "../../src/core/core.utils";
Also I have tried by myself to fix this, and I have read:
Calling a javascript function in another js file
So then I did what Fernando Mendez explains, which is to import the js file in the index.html, as:
<script src="../../src/core/core.utils.js"></script>
So then I commented out the import in the application js:
// import CoreUtils from "../../src/core/core.utils";
And the result is:
Uncaught SyntaxError: Unexpected identifier
In the following line:
import Validators from './core.validators';
Would you be kind and help me a little bit?
In addition my question is related to a previous one:
Javascript Trying to run AMIjs examples in local it does not work
However I do put this separatedly because of I think the problem is with JavaScript and not a Library.
Thank you for reading me.
Are you trying to call the static js function from another js file?
It looks like you have a few problems going on here.
1.) import CoreUtils from "../../src/core/core.utils";
From your example code of CoreUtils, I don't see a exported CoreUtils object from src/core/core_utils.js.
In order to utilize the import statement to reference code in another file, you need to export the object from the original file. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)
This can be accomplished quickly by modifying your function definition in core_utils.js as follows:
change static parseUrl(url) { to export function parseUrl(url) {
Then, in application.js:
change import CoreUtils from "../../src/core/core.utils"; to import {parseUrl} from "../../src/core/core.utils"
It looks like you are running into a similar error with import Validators from './core.validators';
Hope that helps!
Try this:
Your parseUrl(url) function should be public, so change static parseUrl(url) to export function parseUrl(url).
Inside your main javascript file, import it like so:
import { parseUrl } from "../../src/core/core.utils";
And then just use it: var parsed = parseUrl(url);
Also, check this out

NodeJS Express Function not defined

All I'm trying to do is execute geoAutocomplete in browser console so I can console log values from form. I'm getting ReferenceError: geoAutocomplete is not defined error.
const GooglePlaces = require('google-places');
const places = new GooglePlaces("myapikey");
function geoAutocomplete(input, lat, long) {
console.log(input, lat, long);
//const dropdown = places.autocomplete(input);
}
export default geoAutocomplete;
myApp.js
import '../sass/style.scss'
import geoAutocomplete from './modules/geoAutocomplete'
geoAutocomplete( document.querySelector('#address'), document.querySelector('#lat'), document.querySelector('#long') );
layout.pug
script(src='/javascript/vcaApp.js' type='module')
form(method='POST' action='/addGeofence')
h3 Add a Geofence
div.input-field
label(for='address') Address
input(type='text' id='address', placeholder='Address',
required='true', autofocus='true' name='address')
div.input-field(style="display: none;")
input(type='number' id='lat', placeholder='Address',
autofocus='true' name='lat')
div.input-field(style="display: none;")
input(type='number' id='long', autofocus='true' name='long')
Just use module.exports / require. It's hard to tell where the error gets produced as you don't know how you're making the code runable in a browser (neither require nor import are supported there).
The easiest will be to just use
module.exports = getAutocomplete;
and to import the function in the other file
const geoAutocomplete = require('./modules/geoAutocomplete');
Your pre es6 compiler/transpiler/whatever will be able to handle this.

Categories