If I hardcode a javascript module import in my php code, it works:
<script type="module">
import { logFoo1, logFoo2 } "/Root/js/foo.js";
logFoo1();
logFoo2();
</script>
Not very relevant, but just in case, the foo.js:
export function logFoo1() {
console.log('logged from imported js file1');
}
export function logFoo2() {
console.log('logged from imported js file2');
}
The server path is different so I handle that with a variable $rootPath = "/Root"
so that my includes work along the project. Like for ecample <?php include($_SERVER['DOCUMENT_ROOT'] . $rootPath . "/includes/headgeneral.php")?>
How may I add an import with a relative path in my javascript so that there are no hardcoded paths?
I tried:
<?php
$dir = $rootPath . "/js/foo.js;";
echo "dir is $dir"
?>
<script type="module">
import { logFoo1, logFoo2 } from <?php $dir ?>
logFoo1();
logFoo2();
</script>
Althought the string is the same for the pàth, I obtain the error: Uncaught SyntaxError: Unexpected identifier
Imports cannot be resolved out of the php code in the .js files themselves as in node.js and so I would like to know if this is possible, and if this is not the way, what would be the way to structure big amounts of js code if it gets big with php.
source https://stackoverflow.com/questions/68604867/import-javascript-files-with-relative-path-php
Comments
Post a Comment