Using Phoenix 1.4 with webpack, I added "findandreplacedomtext": "^0.4.6" to my package.json file and installed the library.
Now in app.js I have import findAndReplaceDOMText from 'findandreplacedomtext'; and that allows me to use the library, but it only works within the app.js file. I want to be able to use the library in my view templates but whenever I try to use it in a template, I get an error in the console Uncaught ReferenceError: findAndReplaceDOMText is not defined.
This is what the code looks like inside of my template:
<div id="container">
This is a test.
</div>
<script>
findAndReplaceDOMText(document.getElementById('container'), {
find: 'test',
wrap: 'mark'
});
</script>
That throws an error in the console. But if I put the same javascript code in app.js below the library's import statement it works. How can I use the library inside of my view template and outside of app.js?
The error is in your js, you're selecting an element by id 'container' but it's a class, so it should be:
findAndReplaceDOMText(document.getElementsByClassName('container')
At the top of webpack.config.js I put const webpack = require('webpack'); so that in the plugins list I could put new webpack.ProvidePlugin({findAndReplaceDOMText: "findandreplacedomtext"}). This made it so that I could remove the import statement for the library from app.js.
Then, in app.js I put window.findAndReplaceDOMText = findAndReplaceDOMText; in order to expose the module outside of app.js.
Finally, in my template, I had to wrap the function in a content loaded event in order to make sure I wasn't invoking the function before it was loaded.
<script>
document.addEventListener("DOMContentLoaded", function(event) {
findAndReplaceDOMText(document.getElementById('container'), {
find: 'test',
wrap: 'mark'
});
});
</script>
Related
I'm using Laravel with Vite. But I'm having a trouble. I have multiple JS files and including them whenever I want to use. But I cannot use the function I created in one file in another file.
I have an app.js file looks like this:
import jQuery from 'jquery';
window.$ = jQuery;
import './bootstrap';
import './main.js';
import Alpine from 'alpinejs';
window.Alpine = Alpine;
Alpine.start();
And I have a function like this in main.js:
function testFunction() {
alert('test');
}
I put Vite definitions to my layout blade like this:
#vite(['resources/css/app.css', 'resources/js/app.js'])
I have another page contains another JS file like this:
#extends('layouts.app')
#section('content')
#endsection
#section('scripts')
#vite(['resources/js/edit-note-page.js'])
#endsection
And in that JS file I want to use the function that I mentioned in the beginning like this:
testFunction();
But I'm getting an Uncaught ReferenceError: testFunction is not defined error in console. I couldn't figure it out. What is the correct way to do it?
I'm using Laravel with Vite. I have multiple JS files and including them whenever I want to use. But I cannot use the function I created in one file in another file.
Each file is going to be wrapped to actually prevent what you are attempting to do, unless explicitly defined on the window object (notice how window.Alpine = Alpine; is set in your app.js). An alternative and more modern way is to use exports. Here is an example using your file structure.
main.js:
function testFunction() {
alert('test');
}
export default testFunction;
edit-note-page.js:
import testFunction from './path/to/file/name';
...code here
The path to the file in the import does not need the extension .js at the end.
Note: After this change, you no longer need import './main.js'; inside of app.js
I'm trying to import a file into TypeScript that's basically just a js file that you'd put into a tag. I've tried a few different things.
// global.d.ts
declare module 'myfile.js'
Inside of the react file:
// component.tsx
import { foo } from '../lib/myFile.js' // This is saying it is not a module
Inside of the js file, it looks like this a few times so not sure how I need to reference the file:
(function( something ) {
something.Foo = function (){}
}(window.something = window.something || {}));
Any thoughts on how I could use this file? Do I need to go through and declare typings for everything in it?
EDIT: I've added allowJS to my tsconfig but it still doesn't work.
You can only import what is exported from the file.
If your file contains only immediately invoked functions, or top level code, you only need to import the file itself like this:
import '../lib/myFile.js'
This is a little weird, however. I would suggest wrapping everything with a function and exporting then importing that function instead.
Nooby question:
I've got file main.js with module let myModule = {}, defined there inside $(document).ready(function(). And I have another file summary.js where I would like to use it. I declare them all in the head of html file:
<script src="js/main.js"></script>
<script src="js/summary.js"></script>
I would like to use myModule module in the summary.js file and extend it. So I would like to be able to define: myModule.summary = {}. For now I receive the error myModule is undefined even though all js files are uploaded correctly (I can see them in debugger in dev console of the browser). I expect I have to export the mdrx module somehow but export default mdrx at the end of main.js does not do the job. How to do it correctly? I read the documentation but it seems like structural problem as I couldn't figure that out. Can that be that the myModule is not loaded yet before loding summary.js? If so how to prevent that?
You can use the type attribute to achieve this:
<script src="js/main.js" type="module"></script>
Then you can import the module in other JavaScript files:
import yourModule from './main.js'
The problem was that the whole myModule was defined inside function() (called within document.ready event). Moving it outside that solved the problem.
I am trying to load a custom JS file into my vue and I recently came across vue-plugin-load-script and installed it. I configured it as below:
In my main.js I have
Vue.loadScript("file.js").then(() => {
console.log("SUCESS")
}).catch(() => {
console.log("FAILED")
})
however, the npm page does not show how to use your functions in your views. For instances, lets say the file.js had a function called calculateTime(), and I have a view called Home.vue. How would I call the calculateTime() function from my
<script>
export default {
methods : {
** Trying to put function here **
}
}
</script>
If you have you JS File local, you can import it, like:
import * as localA from "./../../theFile.js"; /*put your path to file.js*/
And after that you can use all methods from theFile.js by writting in a method from your vue Component
methodVue: function (...) {
localA.theMethod(param); /*the Method is declared in theFile.js*/
return;
}
And in your theFile.js your method that you want to use need to be written like that
export function theMethod(param) {
...
}
Do you have a specific reason to use this library? Looking at the function all it does is add a script tag to the DOM if it is not already there and resolve the promise when it loads GitHub link. You could just as well use import * from 'file.js' at the top of the vue file. Then use the functions from that file as usual. The bundler should be able to figure out if the file is imported in multiple places and add it only once.
I am including my js file into my main html file like so
<script type="text/babel" src="js/scripts.js"></script>
Then I call one of my functions like so
<div class="allButton" id="completeAll" onclick="showAll('completeColumn');">Show All (...)</div>
the function looks like this
function showAll(column) {
$('div[id^='+column+']').removeClass('hide');
};
When I click the button(div) I get this error
Uncaught ReferenceError: showAll is not defined
I am using the text/babel as my script type because the file contains React JS stuff.
I have no idea why I simply cannot call my function. I am extremely new to ReactJS and Babel. (note: I am not using npm/gulp due to limitations)
Any help and/or advice would be appreciated
If you just define your function as follows you will be able to call it within the HTML.
window.showAll = function showAll(column) {
// your code here...
};
You have not exported your showAll function. When you transpile a JS/JSX file with Babel and bundle it to a scripts.js file (using Browserify or similar utilities), you must make sure to export your module (which tells your bundler to package it into your bundled file).
Your code should look like this:
var showAll = function(column) {
$('div[id^='+column+']').removeClass('hide');
};
module.exports = showAll;
This tells your bundler that your showAll method needs to be exported and available to other referenced namespaces.