How to link to different pages in JS?
See original GitHub issue🤔 Question:
I was wondering how you create links to other HTML pages from JS.
Say I have two files, a.html
and b.html
and a JS file in a.html
with this:
const link = document.createElement("a");
link.setAttribute("href", "./b.html");
link.textContent = "JS link";
document.body.appendChild(link);
Since the built files all get put in the dist
folder without any folder structure and hashed names, how do you actually reference other static files? I know you handle src
for images by importing the image file in JS as a dependency, but what about HTML files? I’ve tried b.html
, ./b.html
, but none work.
🎛 Configuration (.babelrc, package.json, cli command)
{
"name": "parcel-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "parcel a.html"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"parcel-bundler": "^1.5.0"
}
}
🤔 Expected Behavior
Clicking on the generated link takes me to b.html
.
😯 Current Behavior
Clicking on the link changes the address in the browser to localhost:1234/b.html
but doesn’t actually load that file.
💁 Possible Solution
Maybe preserve file names so links created in JS will work? Or am I missing something obvious here? 😰
🔦 Context
I’m loading some (external) data through JavaScript and I want to create links to the appropriate pages depending on the data I’ve loaded in.
💻 Code Sample
None
🌍 Your Environment
Software | Version(s) |
---|---|
Parcel | 1.5 |
Node | 8.9.3 |
npm/Yarn | 5.6.0 |
Operating System | macOS 10.13.3 |
Issue Analytics
- State:
- Created 6 years ago
- Reactions:2
- Comments:17 (6 by maintainers)
@davidnagli: I am new parcel.js and frontend development in general. I am trying to do as you suggested and trying to import the html. I keep getting an error with my import statement. Since I am new to parcel and CommonJS, I am probably not structuring the import correctly. In my case I am trying to import an file that is 2 directories up from the file where the import statement is located. My import statement looks something like this:
I keep getting the error: “Cannot find module”. Is there something different I should be doing with my import statement?
Upon further review and discussion, I think that this feature isn’t very useful, and would be nearly impossible to implement.
You can accomplish the exact same thing by importing the html, which will return a URI. For example:
It’s just a string with the URI, so you can use it in any way you want:
Importing HTML files (at least in Parcel 1.x) will always resolve that file and return a URI pointing to it, not the actual file contents.
Note: This also works in the same exact way with CommonJS require