import javascript files with relative path php
one text
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.
Edit:
This works: import { logFoo1, logFoo2 } from "<?php echo $rootPath?>/js/foo.js"
While this does not: import { logFoo1, logFoo2 } from "<?php echo $rootPath . "/js/foo.js;"?>"
Throwing an error: net::ERR_ABORTED 404 (Not Found)
Seems like the foo script is not found.
Why? Doesnt php resolve then string concatenation and the the built script is run in the client(browser)?
Source