I'm using the glob import functionality of Vite to bring in multiple markdown files to a SvelteKit page:
<script context="module">
export async function load() {
const employmentsMeta =
import.meta.globEager('./employments/*.md');
return {
props: {
employmentsMeta: employmentsMeta
}
};
}
</script>
<script>
export let employmentsMeta;
</script>
This works well for me to access the metadata via employmentsMeta[Object.keys(employmentsMeta)[0]]['metadata']. I'm having difficulty accessing the actual contents of the markdown file, however - no matter how I attempt to access it, it seems to be coming back as undefined.
For example, console.log(employmentsMeta[Object.keys(employmentsMeta)[0]['default']]) returns undefined, despite my understanding that there's a default export object in there, and the metadata access working as intended.
How do I access the payload / body of the imported markdown?
I have a similar use-case, with markdown files in SvelteKit as blog posts.
In your example, I'd get the file contents as html like this:
const contents = employmentsMeta[Object.keys(employmentsMeta)[0]].default.render();
contents here is an object like this:
{
html: '/* a string with the markdown content parsed as html */',
css: { code: '', map: null },
head: '',
}
I guess you have to use mdsvex for the md->html conversion to happen.
EDIT: I should mention that I do this in an endpoint ([slug].json.js), return the results, and get them in the route, as doing it in the load function was throwing an error (...default.render is not a function) client-side.
Related
In my standard React app, I need to achieve the following: import a file that sits within my src folder, in order to simply read its content as a string. For example, let's say I have the following code in a file:
alert('hey')
then in some other file, I would like to do something like this, in pseudo code:
import * as string from './someFile.js'
console.log(string)
The output of the console.log should be the JS code, as a string:
alert('hey')
If I could place the file within my public folder, I'd be able to perform an http request and read it as I wish. But the problem is of course, that the file is part of the build process(inside the src folder)
Can this be done?
i can think about:
define constants.js file with following code:
export default "alert('vasia')";
import this file from some react file:
import vasia from "./constants";
const App = () => {
console.log(eval(vasia));
}
is that what you r searching for?
But, must warn you: "eval" is evil!
I wanted to do the very same thing but unfortunately found out it is not possible in pure JS as at 2022.
There's a stage 3 TC39 proposal for Import Assertions which is available in Chromium-based browsers but only allows to import JSON files so it certainly would not help in this particular case.
I believe your best bet for now is to use Fetch API to get the content of your file asynchronously.
async function getSampleText() {
const response = await fetch('someFile.js');
console.log(
await response.text()
);
}
I want to fetch files from another server (e.g. a CDN) with the #nuxtjs/content module so that the .md files can be managed independently without Nuxt.js.
My current nuxt.config.js file looks like this:
export default {
...
content: {
dir: 'http://some-cdn.xyz/content/'
},
...
}
Now I want to load the content in the pages/_slug.vue file:
<template>
<div>
<NuxtContent :document="doc" />
</div>
</template>
<script>
export default {
async asyncData({ $content, params }) {
const doc = await $content(params.slug || 'index').fetch();
return { doc };
},
};
</script>
Now when I type in http://localhost:3000/some-page, I should get the corresponding file (some-page.md) from the CDN. Instead, I get this error from Nuxt.js: /some-page not found.
What should I do to get it working and is this even possible with my current setup?
As told here: https://github.com/nuxt/content/issues/237
This is not doable with the content module and is not planned to be done neither. A solution would be to manually fetch the files during the build time or alike.
You can maybe get some inspiration from this comment: https://github.com/nuxt/content/issues/37#issuecomment-664331854 or use another markdown parser.
Since #nuxtjs/content can't fetch files from another server, I used the marked.js library instead.
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 (very) new to React and have been given the task of adding some data to a component that's being brought in from another file. This file spits out some JSON and I want to access certain pieces of data from it, for example:
config.forms.enquiry.title
I am importing the file fine - no problems there. But I am not sure how to include config into my props.
I found a working example, in another file, and have copied what it does. My code is as such
Brings in file with JSON:
import { withSettings } from 'services/settingsFile';
Add config in render function:
render () {
const styles = getStyles(this.props, this.context, this.state);
const { config } = this.props;
// other stuff
Add to propTypes:
enquiryForm.propTypes = {
config: PropTypes.object.isRequired,
// other stuff
Add to compose:
export const enquiryForm = compose(
withSettings,
// other stuff
However, I get the error:
Failed context type: The context config is marked as required in
n, but its value is undefined.
And from here I am not sure what to do. I know it's a tough question, but I know very little about React and have been thrown in the deep end.
Would anyone know what/where I should be searching for to fix this?
If you can import it like,
import { withSettings } from 'services/settingsFile';
why dont you use it like,
const { config } = withSettings;
OK, so the issue was that there was no wrapping element setting config as am attribute.
I had to go up a level to where my component was being brought in and wrap:
<SettingsFile config={window.settingsFile}>
around:
<Component conf={config} />
Then, the component I was working on was able to read config.
I'm having a number of issues putting together a very simple piece of code as I learn Meteor. See the comments, which are questions.
server/main.js
import { Meteor } from 'meteor/meteor';
import { Post } from './schema'
// Why is this required to make Post available in Meteor.startup?
// Isn't there auto-loading?
Meteor.startup(() => {
console.log(Post)
// This works, but why isn't Post available to meteor shell?
});
server/schema.js
import { Post } from './models/post'
export { Post }
server/models/post.js
import { Class } from 'meteor/jagi:astronomy';
// Why can't this be imported elsewhere, like main.js?
const Posts = new Mongo.Collection('posts');
const Post = Class.create({
name: 'Post',
collection: Posts,
fields: {
title: { type: String },
userId: String,
publishedAt: Date
},
});
export { Post }
In addition to these questions, how can I load my app into meteor shell? Post is undefined there, even though it's defined in Meteor.startup. I tried using .load with an absolute path, but this breaks my app's imports, which use relative paths.
As for which errors I'm confused about:
When I try and use import inside Meteor.startup(), I get an error that the keyword import is undefined. I'm using the ecmascript package.
When I don't import { Class } in the same file where I use Class, I get an unknown keyword error.
If I don't import { Post } in main.js, then Post is undefined.
Not able to load app into Meteor shell.
To access exported objects in Meteor shell, use require:
> require('server/schema.js').Posts.findOne();
To access objects exported by packages, use the package name:
> require('react').PropTypes;
The reason you can't access an object that's imported by another js file is that each file has its own scope here. When Meteor builds your app, it doesn't just concatenate js files like many other build systems do, and that's really a good thing.
Basically a Javascript object gets created for every js file you write. Anything you export in a js file becomes a field in this object which you can access by using require. And import is just a nicer version of the same thing.