How to use `svelte-spa-router` when `customElement: true`? - components

I use it like this:
<script>
import Router from "svelte-spa-router";
</script>
<Router routes={{}} />
and I got some compile-time warn and runtime error:
compile-time warn
runtime error
ah, and, when I trying to use other components that haven't <svelte:options tag="xxx" /> tag, I got those warn/error too.
so...how?

You should set tag as "xxx-yyy";
Set svelte({
compilerOptions: {
customElement: true
}})
in vite or rollup config

Related

How to mock nuxt build module in jest

TLDR; Need help with mocking a nuxt build module in jest.
I declared a module in nuxt config like this to be globally accessible
// nuxt.config.ts
{
buildModules: [
'#nuxtjs/moduleA',
]
}
This build module is used by a component that is itself used everywhere throughout the app.
<script>
// TheComponent.vue
export default {
name: 'TheComponent',
computed: {
calculation() {
return this.moduleA.key === value
}
}
}
</script>
At the parent level
<template>
<div>
<!-- ... -->
<TheComponent :props="props" />
<!-- ... -->
</div>
</template>
I keep getting this error when running the tests:
[Vue warn]: Error in render: "TypeError: Cannot read property '<property>' of undefined"
What is the best way to declare the build module such that jest doesn't complain at the parent component level that moduleA doesn't exist?

Deploying NextJS project to my own server (npm run build triggers module not found error)

I have built a NextJS project and I'm ready to deploying it to a staging server for testing (running AlmaLinux 8). I have installed node version 16.8.0.
I've copied the entire contents of my project to my server and run npm run build but I then get the error:
build
> next build
info - Loaded env from /var/www/html/CrashCatch/CrashCatchDocs_Testing/.env
Failed to compile.
./pages/[...].tsx:2:23
Type error: Cannot find module '../components/TopHeader' or its corresponding type declarations.
1 | import Head from 'next/head'
> 2 | import TopHeader from "../components/TopHeader";
| ^
3 | import Link from 'next/link'
4 | import {useRouter} from "next/router";
5 | import {getSlugFromUrl} from "../JSFuncs/HelperFunctions";
Below is a screenshot showing the directory structure
In the `./pages[...].tsx I have the following
import Head from 'next/head'
import {getSlugFromUrl} from "../JSFuncs/HelperFunctions";
import UserHelpContainer from "../components/Articles/UserHelpContainer";
import UserSidebar from "../components/Sidebar/UserSidebar";
import useArticle from "../hooks/useArticle";
import {useEffect, useState} from "react";
import useCrashCatch from "../hooks/useCrashCatch";
import TopHeader from "../components/TopHeader";
export default function Home() {
const slug = getSlugFromUrl();
const {loading, publishedArticle, errors, refetch} = useArticle(slug);
const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false);
const {crashcatch} = useCrashCatch('12345', "123456", "1.0.0");
useEffect(() => {
(
async function() {
await refetch();
}
)();
}, [slug]);
return (
<>
<div className="w-full h-full min-h-full overflow-none absolute">
<Head>
<title>Crash Catch Documentation</title>
<link rel="icon" href="/favicon.ico" />
<meta name='description' content={publishedArticle !== null && typeof publishedArticle !== typeof undefined ? publishedArticle.metaDescription : ''} />
<meta name='keywords' content={publishedArticle !== null && typeof publishedArticle !== typeof undefined ? publishedArticle.metaKeywords : ''} />
</Head>
<TopHeader mobileSidebarOpen={mobileSidebarOpen} setMobileSidebarOpen={setMobileSidebarOpen} />
<div className='flex flex-row h-full overflow-y-scroll'>
<UserSidebar slug={slug} mobileSidebarOpen={mobileSidebarOpen} setMobileSidebarOpen={setMobileSidebarOpen} />
<UserHelpContainer slug={slug} loading={loading} errors={errors} article={publishedArticle} />
</div>
</div>
</>
)
}
And in the TopHeader I have the following:
I am declaring TopHeader as follows (I've not included the whole thing as don't think its relevant)
const TopHeader = React.memo(function TopHeader(props: TopNavProps)
If the path is correct, you might not be exporting TopHeader as default?
export default TopHeader; // This will allow for generic import
And then to import:
import TopHeader from '../components/TopHeader'; // Can now use TopHeader
Edit: Included code blocks, cleaned answer and moved ramble to bottom...
I have never answered a question, so I planned on just commenting as this is more or less a question... But I must have more reputation to comment... Apologies..
I figured out my problem, thanks for the suggestions as it made me look at something and figure out the issue.
It was a rather dumb reason, where my SFTP client didn't fully upload and instead asked me a question which was hidden, so I didn't see it and therefore, only the top level directories uploaded, but deeper directories were missing some files hence the module not found error.
After getting this to work it it was an issue with CSS, this was to do with Tailwind purging CSS classes so had to add the following to tailwindcss.confnig.js
module.exports = {
purge:{
enabled: true,
content: [
'./pages/**/*.{js,ts,jsx,tsx}',
'./components/**/*.{js,ts,jsx,tsx}',
'./components/*.{js,ts,jsx,tsx}',
'./JSFuncs/*.{js,ts,jsx,tsx}'
// Add more here
]
},

Svelte: Disable ESLint Rule

I'm working on a Svelt project that uses ESlint, and I'm trying to disable a rule within my svelte template but can't find any information on how to do so. My code is the following:
<script lang="ts">
const unsubscribe = promiseWritable.subscribe((value) => {
promise = value;
});
onDestroy(unsubscribe);
</script>
{#if !!promise} <---- ESLint error here!
{#await promise then promiseResult}
<Info {promiseResult} />
{/await}
{/if}
This results in {#if !!promise} having the ESLint error:
Expected non-Promise value in a boolean conditional.eslint#typescript-eslint/no-misused-promises)
Regardless of whether I should disable this rule, I'm wondering how I would disable it within the file since adding either:
// eslint-disable-next-line... or <!-- eslint-disable-next-line... -->
above the line won't disable the error.
For Reference I am using https://github.com/sveltejs/eslint-plugin-svelte3
Since this commit, you can now add a "magic comment" to your Svelte file to disable individual validations using the form <!-- svelte-ignore rule-name -->.
<!-- svelte-ignore a11y-mouse-events-have-key-events -->
<div on:mouseover={mouseOver} on:mouseleave={mouseLeave} class="wrapper">
<slot name="content" />
</div>
The eslint-plugin-svelte plugin works fine with <!-- eslint-disable --> directives in svelte templates.
https://github.com/ota-meshi/eslint-plugin-svelte
I found a somewhat unsatisfying solution by adding /* eslint-disable */ to the bottom of the script tag giving us:
<script lang="ts">
const unsubscribe = promiseWritable.subscribe((value) => {
promise = value;
});
onDestroy(unsubscribe);
/* eslint-disable */
</script>
{#if !!promise} <---- No ESLint error anymore
{#await promise then promiseResult}
<Info {promiseResult} />
{/await}
{/if}
This will disable all linting in the HTML template.
You can set the settings.svelte3/named-blocks to true in your eslint config. Docs on svelte3/named-blocks. Then modify the targetted svelte files in overrides, and add template into ignorePatterns.
Such way requires no ...eslint-disable... in source files.
# .eslintrc.cjs
...
ignorePatterns: [
"**/*.svelte/*_template.ts",
],
overrides: [{ files: ["**/*.svelte/*.ts"], processor: "svelte3/svelte3" }],
settings: {
"svelte3/typescript": () => require("typescript"),
"svelte3/named-blocks": true,
},
...
Related GitHub issue

next.js + expo: You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports

When I try to run yarn ios, I get:
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check the render method of `MyApp`.
But my App.tsx, has:
class MyApp extends App {
render() {
const { Component, pageProps } = this.props;
return (
<ThemeProvider theme={theme}>
<ScrollView>
<Component {...pageProps} />
</ScrollView>
<FooterBar />
</ThemeProvider>
)
}
}
export default MyApp
So I'm not sure what it's complaining about?
Try importing the component directly from its origin and plugging in your pageProp after. So in example :
import {Component} from '../pathOfComponent';
You most likely are not passing anything in this.props.Component. Javascript is quite tricky, if the element does not exist it will treat it as undefined

How to Load Multiple React Components Dynamically?

Hi I'd like to load multiple react components from a directory dynamically. Such that somebody only has to add a component in a directory for it to be loaded. I'm thinking something along the lines like:
import * as dynamicComponents from './dynamicComponents';
const toAdd = [] dynamicComponents.forEach(function(component){
toAdd.push( Route path={component.link} component={component.implmentation} /> })
render(<Provider store={store}>
<Router history={history}>
<Route path="/" component={Template}>
<IndexRoute component={Main} />
{toAdd}
</Route>
</Router>
</Provider>,
document.getElementById('root') );
Is this possible?
I believe your first import statement won't work in Babel. Try this package:
npm i --save-dev babel-plugin-wildcard
Add it to your .babelrc with:
{
"plugins": ["wildcard"]
}
You may not be using Babel in your environment, but essentially you need to solve the the problem of loading from a wildcard or dynamic path. That is probably the hard part.
You'll also need to be sure that every file dropped into the directory exports a React component class as its default export and has a static function returning a link.
const SomeReactComponent = () => (<p>Rendering something.</p>);
//Export link as static member of the class.
SomeReactComponent.link = '/some/react/component/routing/link';
export default SomeReactComponent;
Then code like the following will work at compile-time:
import * as dynamicComponents from './dynamicComponents';
const toAdd = dynamicComponents.map( (ComponentClass) => <Route path={ComponentClass.link} component={ComponentClass} /> );
This is a compile-time solution. If you want a run-time solution, investigate using importers other than ES6 import, which I believe cannot be used dynamically at run-time.

Resources