Local docusaurus plugins in typescript - docusaurus

I want to write local docusaurus plugins using typescript. (it works fine using js)
Is this possible? Like the docs here suggest to put them under ./src/plugins/name-of-plugin.
Reading the docs there are examples with ts, but if I just try and replace is with ts i get various errors. (eg "Cannot find module").
I'm using typescript for pages as well.

Adding the file extension worked for me.
For example:
plugins: ['./src/plugins/my-plugin.ts'],
my-plugin.ts
module.exports = async function myPlugin(context, options) {
return {
name: "my-plugin",
async loadContent() {
console.log("Hello World plugin wow!");
},
async contentLoaded({ content, actions }) {
console.log(content);
},
};
};
removing the extension shows the same error :)

Related

Is it possible to use DayJs in ant design Vue (antdv) in DatePickers instead of MomentJs?

I tryed to replace momentjs in project on antdv, and find this advice:
"We also provide another implementation, which we provide with
antd-dayjs-webpack-plugin, replacing momentjs with Day.js directly
without changing a line of existing code. More info can be found at
antd-dayjs-webpack-plugin."
https://2x.antdv.com/docs/vue/faq
So then i tryed to do same steps like in instruction https://github.com/ant-design/antd-dayjs-webpack-plugin. But i just changed webpack-config.js on vue-config.js and in code:
const AntdDayjsWebpackPlugin = require('antd-dayjs-webpack-plugin');
module.exports = {
plugins: [
new AntdDayjsWebpackPlugin()
]
}
// on
const AntdDayjsWebpackPlugin = require('antd-dayjs-webpack-plugin');
module.exports = {
configureWebpack: (config) => {
config.plugins.push(
new AntdDayjsWebpackPlugin(),
);
}
}
But then i got mistake 502 Bad Gateway.
If i deleted configureWebpack mistake was still there. And then i deleted require and mistake was gone.
Also i found what in page with this plugin there was word about React but not about Vue.
So i had few questions:
Is it possible to use DayJs in antdv DatePickers? With plugins or any ways.
Is it mistake in FAQ? How i can tall about this issue (if it is)? I didnt found any method to communicate with them.

How to embed html/js widgets in Nuxt, specifically iFlyChat but broadly applicable

I have a couple of plugin widgets that I'd like to integrate into my site but I'm wondering how best to do it to preserve the Nuxt functionality like code-splitting, etc. For example, the code below is for iFlyChat. When I first used the code in my appHeader, it worked, then was intermittent for a while but now doesn't show up at all:
<script>
var iflychat_app_id="xyzappidcode";
var iflychat_external_cdn_host="cdn.iflychat.com",iflychat_bundle=document.createElement("SCRIPT");iflychat_bundle.src="//"+iflychat_external_cdn_host+"/js/iflychat-v2.min.js?app_id="+iflychat_app_id,iflychat_bundle.async="async",document.body.appendChild(iflychat_bundle);var iflychat_popup=document.createElement("DIV");iflychat_popup.className="iflychat-popup",document.body.appendChild(iflychat_popup);
</script>
I've since tried a similar widget for edwid but that didn't show up on the page at all.
You have to create a nuxt plugin to init your code on each page.
Fist, create a file plugins/iflychat.js:
export default () => {
console.log("init iflychat plugin");
var iflychat_app_id = "xyzappidcode";
var iflychat_external_cdn_host="cdn.iflychat.com",iflychat_bundle=document.createElement("SCRIPT");iflychat_bundle.src="//"+iflychat_external_cdn_host+"/js/iflychat-v2.min.js?app_id="+iflychat_app_id,iflychat_bundle.async="async",document.body.appendChild(iflychat_bundle);var iflychat_popup=document.createElement("DIV");iflychat_popup.className="iflychat-popup",document.body.appendChild(iflychat_popup);
}
Then, configure Nuxt.js to import it:
//nuxt.config.js
export default {
plugins: [
{ src: '~plugins/iflychat.js', mode: 'client' }
]
}
That's it, you iFlatChat will run on every page view.

“window is not defined” in Nuxt.js

I get an error porting from Vue.js to Nuxt.js.
I am trying to use vue-session in node_modules. It compiles successfully, but in the browser I see the error:
ReferenceError window is not defined
node_modules\vue-session\index.js:
VueSession.install = function(Vue, options) {
if (options && 'persist' in options && options.persist) STORAGE = window.localStorage;
else STORAGE = window.sessionStorage;
Vue.prototype.$session = {
flash: {
parent: function() {
return Vue.prototype.$session;
},
so, I followed this documentation:
rewardadd.vue:
import VueSession from 'vue-session';
Vue.use(VueSession);
if (process.client) {
require('vue-session');
}
nuxt.config.js:
build: {
vendor: ['vue-session'],
But I still cannot solve this problem.
UPDATED AUGUST 2021
The Window is not defined error results from nodejs server side scripts not recognising the window object which is native to browsers only.
As of nuxt v2.4 you don't need to add the process.client or process.browser object.
Typically your nuxt plugin directory is structured as below:
~/plugins/myplugin.js
import Vue from 'vue';
// your imported custom plugin or in this scenario the 'vue-session' plugin
import VueSession from 'vue-session';
Vue.use(VueSession);
And then in your nuxt.config.js you can now add plugins to your project using the two methods below:
METHOD 1:
Add the mode property with the value 'client' to your plugin
plugins: [
{ src: '~/plugins/myplugin.js', mode: 'client' }
]
METHOD 2: (Simpler in my opinion)
Rename your plugin with the extension .client.js and then add it to your plugins in the nuxt.config.js plugins. Nuxt 2.4.x will recognize the plugin extension as to be rendered on the server side .server.js or the client side .client.js depending on the extension used.
NOTE: Adding the file without either the .client.js or .server.js extensions will render the plugin on both the client side and the server side. Read more here.
plugins: ['~/plugins/myplugin.client.js']
There is no window object on the server side rendering side. But the quick fix is to check process.browser.
created(){
if (process.browser){
console.log(window.innerWidth, window.innerHeight);
}
}
This is a little bit sloppy but it works. Here's a good writeup about how to use plugins to do it better.
Its all covered in nuxt docs and in faq. First you need to make it a plugin. Second you need to make your plugin client side only
plugins: [
{ src: '~/plugins/vue-notifications', mode: 'client' }
]
Also vendor is not used in nuxt 2.x and your process.client not needed if its in plugin with ssr false
In Nuxt 3 you use process.client like so:
if (process.client) {
alert(window);
}
If you've tried most of the answers here and it isn't working for you, check this out, I also had the same problem when using Paystack, a payment package. I will use the OP's instances
Create a plugin with .client.js as extension so that it can be rendered on client side only. So in plugins folder,
create a file 'vue-session.client.js' which is the plugin and put in the code below
import Vue from 'vue'
import VueSession from 'vue-session'
//depending on what you need it for
Vue.use(VueSession)
// I needed mine as a component so I did something like this
Vue.component('vue-session', VueSession)
so in nuxt.config.js, Register the plugin depending on your plugin path
plugins:[
...
{ src: '~/plugins/vue-session.client.js'},
...
]
In index.vue or whatever page you want to use the package... import the package on mounted so it is available when the client page mounts...
export default {
...
mounted() {
if (process.client) {
const VueSession = () => import('vue-session')
}
}
...
}
You can check if you're running with client side or with the browser. window is not defined from the SSR
const isClientSide: boolean = typeof window !== 'undefined'
Lazy loading worked for me. Lazy loading a component in Vue is as easy as importing the component using dynamic import wrapped in a function. We can lazy load the StepProgress component as follows:
export default {
components: {
StepProgress: () => import('vue-step-progress')
}
};
On top of all the answers here, you can also face some other packages that are not compatible with SSR out of the box and that will require some hacks to work properly. Here is my answer in details.
The TLDR is that you'll sometimes need to:
use process.client
use the <client-only> tag
use a dynamic import if needed later on, like const Ace = await import('ace-builds/src-noconflict/ace')
load a component conditionally components: { [process.client && 'VueEditor']: () => import('vue2-editor') }
For me it was the case of using apex-charts in Nuxt, so I had to add ssr: false to nuxt.config.js.

Upload images with apollo-upload-client in React Native

I'm trying out Prisma and React Native right now. Currently I'm trying to upload images to my db with the package _apollo-upload-client (https://github.com/jaydenseric/apollo-upload-client). But it's not going so well.
Currently I can select an image with the ImagePicker from Expo. And then I'm trying to do my mutation with the Apollo Client:
await this.props.mutate({
variables: {
name,
description,
price,
image,
},
});
But I get the following error:
Network error: JSON Parse error: Unexpected identifier "POST"
- node_modules/apollo-client/bundle.umd.js:76:32 in ApolloError
- node_modules/apollo-client/bundle.umd.js:797:43 in error
And I believe it's from these lines of code:
const image = new ReactNativeFile({
uri: imageUrl,
type: 'image/png',
name: 'i-am-a-name',
});
Which is almost identical from the their example, https://github.com/jaydenseric/apollo-upload-client#react-native.
imageUrl is from my state. And when I console.log image I get the following:
ReactNativeFile {
"name": "i-am-a-name",
"type": "image/png",
"uri": "file:///Users/martinnord/Library/Developer/CoreSimulator/Devices/4C297288-A876-4159-9CD7-41D75303D07F/data/Containers/Data/Application/8E899238-DE52-47BF-99E2-583717740E40/Library/Caches/ExponentExperienceData/%2540anonymous%252Fecommerce-app-e5eacce4-b22c-4ab9-9151-55cd82ba58bf/ImagePicker/771798A4-84F1-4130-AB37-9F382546AE47.png",
}
So something is popping out. But I can't get any further and I'm hoping I could get some tips from someone.
I also didn't include any code from the backend since I believe the problem lays on the frontend. But if anyone would like to take a look at the backend I can update the question, or you could take a look here: https://github.com/Martinnord/Ecommerce-server/tree/image_uploads.
Thanks a lot for reading! Cheers.
Update
After someone asked after the logic in the server I have decided to past it below:
Product.ts
// import shortid from 'shortid'
import { createWriteStream } from 'fs'
import { getUserId, Context } from '../../utils'
const storeUpload = async ({ stream, filename }): Promise<any> => {
// const path = `images/${shortid.generate()}`
const path = `images/test`
return new Promise((resolve, reject) =>
stream
.pipe(createWriteStream(path))
.on('finish', () => resolve({ path }))
.on('error', reject),
)
}
const processUpload = async upload => {
const { stream, filename, mimetype, encoding } = await upload
const { path } = await storeUpload({ stream, filename })
return path
}
export const product = {
async createProduct(parent, { name, description, price, image }, ctx: Context, info) {
// const userId = getUserId(ctx)
const userId = 1;
console.log(image);
const imageUrl = await processUpload(image);
console.log(imageUrl);
return ctx.db.mutation.createProduct(
{
data: {
name,
description,
price,
imageUrl,
seller: {
connect: { id: userId },
},
},
},
info
)
},
}
Solution has been found.
I am a little embarrassed that this was the problem that I faced and I don't know if I should even accept this answer because of awkward I felt when I fixed the issue. But....
There was nothing wrong with my code, but there was a problem with the dependencies versions. I tried to backtrack everything on my app, so I decided to start from the beginning and create a new account. I expected it to work just fine, but I got this error:
Error: Cannot use GraphQLNonNull "User!" from another module or realm.
Ensure that there is only one instance of "graphql" in the node_modules
directory. If different versions of "graphql" are the dependencies of other
relied on modules, use "resolutions" to ensure only one version is installed.
https://yarnpkg.com/en/docs/selective-version-resolutions
Duplicate "graphql" modules cannot be used at the same time since different
versions may have different capabilities and behavior. The data from one
version used in the function from another could produce confusing and
spurious results.
Then I understand that something (that I didn't think of) was wrong. I checked my dependencies versions and compared them with Graphcool's example, https://github.com/graphcool/graphql-server-example/blob/master/package.json. And I noticed that my dependencies was outdated. So I upgraded them and everything worked! So that was what I had to do. Update my dependencies.
Moral of the story
Always, always check your damn dependencies versions...
Crawling through your code, I have found this repository, which must be the front-end code if I am not mistaken?
As you've mentioned, apollo-upload-server requires some additional set-up and same goes for the front-end part of your project. You can find more about it here.
As far as I know, the problematic part of your code must be the initialisation of the Apollo Client. From my observation, you've put everything Apollo requires inside of src/index folder, but haven't included Apollo Upload Client itself.
I have created a gist from one of my projects which initialises Apollo Upload Client alongside some other things, but I think you'll find yourself out.
https://gist.github.com/maticzav/86892448682f40e0bc9fc4d4a3acd93a
Hope this helps you! 🙂

gulp-durandal TypeError: req.toUrl is not a function

I try to implement gulp to my durandal project as explain on Durandal gulp doc
main.js file is successfully build, but when trying to click something that will open a modal dialog, it will show this error (firefox):
TypeError: req.toUrl is not a function
url = req.toUrl(nonStripName),
main.js (line 48306, col 16)
here my configuration on gulpfile.js
var gulp = require('gulp');
var durandal = require('gulp-durandal');
gulp.task('default', function(cb)
{
durandal({
baseDir: 'public_html/app',
main: 'main.js',
output: 'main.js',
almond: true,
minify: false
})
.on('error', function(err) {
console.error('error. ' + err);
})
.pipe(gulp.dest('public_html/build'))
.on('end', cb);
});
I'm also came across with this answer https://stackoverflow.com/a/23329383/1889014
But i'm not sure if this is related to my issue.
Can someone please help or guide me through this ? Thanks!
I also had this issue using gulp, Durandal and modal dialogs. Adding a getView function to the viewmodel that returns the url for the view fixes it.
eg
function getView() {
return "views/theView.html";
}
I am sure there must be a better way of solving this problem but this seems to work in the few places I have needed it.
I have experienced this error due to writing the view name using the wrong case. E.g. if the file is called myView.html but you require 'MyView'.
I am not building using gulp-durandal because it's giving very odd errors, and requirejs is working much better directly. I fixed this error by including all views manually in my requirejs build config.
include: [
'text!customWidgets/alertsSection/title.html', //custom
'text!customWidgets/alertsSection/body.html', //custom
'text!customWidgets/exclusions/body.html', //custom
'text!customWidgets/exclusions/title.html', //custom
'text!customWidgets/submit/body.html', //custom
'text!customWidgets/submit/title.html', //custom
]
There are many more files in my include due to the nature of durandal and the dynamic loading of views... but I don't want to spam everyone :)