error: Relative import path "reflect-metadata" not prefixed with / or ./ or ../ - es6-modules

I'm trying to start making discord bots with Deno and TypeScript. I'm new to Deno and have no idea how to import packages. I tried a lot of things. But most of the time I get this error:
error: Relative import path "reflect-metadata" not prefixed with / or ./ or ../ from "https://unpkg.com/discordx#9.0.1/build/esm/index.js"
at https://unpkg.com/discordx#9.0.1/build/esm/index.js:1:8
My current code is this:
import { Client } from "https://unpkg.com/discordx#9.0.1/build/esm";
const client: Client = new Client({
intents: ["GUILDS", "GUILD_MESSAGES"],
});
console.log("done");

Related

Returning json from .csv asset in nuxt api

Using Nuxt 3, I am struggling to do something that appears simple: I would like to get a list of restaurants from an api served by nuxt/nitro in order to use it on the client side. My original file, is a .csv file stored under assets/: assets/list.csv.
Here is what I have in my component .vuefile:
//...
const { restaurants } = await useFetch('/api/restaurants')
//...
And the content of server/api/restaurants.js:
import csv from 'csvtojson'
export default defineEventHandler(async(event) => {
const data = await csv().fromFile('~/assets/list.csv')
return { data }
})
But I get an error "[500] File does not exist". I've tried many variants but always get an error here or there. Could you help me figure out the solution? Thanks.
Actually solved by realizing the following:
As the doc suggests, the assets/ directory is for assets that are processed by the bundler (Vite or Webpack). Nuxt won't serve files in the assets/ directory unless nuxt.config.ts is configured with the appropriate loader (e.g. a csv loader). Hence the 500 error.
Nuxt Content, on the other hand, is useful to automatically parse a .csv file located in the content/ directory:
In nuxt.config.ts:
modules: ["#nuxt/content"]
In the component .vue file, the following will expose the parsed csv in data.body:
const { data } = await useAsyncData("list", () => queryContent("/list").findOne())
The beauty of nuxt is that you don't need to import anything, it does it for you.

How to use 'discord.js' module in SvelteKit? "require is not defined" error occurrs

I'm trying to use discord.js module to develop a Discord bot in SvelteKit.
In the Discord official example, "discord.js" can be used with following code,
const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
However, "require is not defined" in SvelteKit as only import is valid syntax with Vite.
Then, how can I use discord.js module in SvelteKit?
Env:
SvelteKit (with TypeScript) version: latest version on August 23, 2022 ("svelte": "^3.44.0",)
Default settings used (e.g. svelte.config.js, tsconfig.json)
discord.js version: 14
What I have done:
Change the require to import => "Failed to fetch dynamically imported module"
Install discord.js with devDependencies
Try using trick as shown below => Module "module" has been externalized for browser compatibility. Cannot access "module.createRequire" in client code.
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
Similar quetions I found:
'require' is not defined - Sveltekit with typescript
require is not defined
How can i import thing in js ? (discord.js)
This probably only runs on an endpoint (i.e. on the server).
Make sure the import statement has the correct form:
import { REST, Routes } from 'discord.js';
The vite.config.js apparently needs to be adjusted because the package or one of its dependencies uses the BigInt data type which is only available in newer versions of JS:
const config = {
plugins: [sveltekit()],
build: {
target: ['es2020'],
},
optimizeDeps: { esbuildOptions: { target: 'es2020' } },
}

svelte - reading json file from local folder

My svelte app is required to read json file from the public folder.
I followed exactly the rollup setup from this link, then add json to my app.svelte:
import * as port from '/port.json';
port.json is located at the public folder together with index.html.
But I keep getting this error:
main.js:11 Uncaught ReferenceError: port is not defined at main.js:11
and I am getting this message from Terminal which I am not sure what it means:
(!) Missing global variable name Use output.globals to specify browser
global variable names corresponding to external modules /port.json
(guessing 'port')
How can I resolve this?
You have two options.
Move the file to your src/ folder and bundle it with the rest of your application code using Rollup. This is where you need #rollup/plugin-json to bundle json files. You can then import it like so:
<script>
import json from './port.json';
</script>
<p>{JSON.stringify(json)}</p>
Keep the file in your public/ folder and retrieve it at runtime using fetch.
<script>
let fetchJson = fetch('port.json').then(res => res.json());
</script>
{#await fetchJson}
<p>Loading JSON</p>
{:then result}
<p>{JSON.stringify(result)}</p>
{/await}
Export the object and rename the file from .json to .json.js.
port.json.js
export let myJson = {
name: "hello world"
}
Component:
<script>
import json from './port.json';
</script>
<p>{JSON.stringify(json)}</p>

How do I create a "fat" js file with rollup using esm?

I have the following code..
// ui.js (generated by rollup
import Vue from 'vue';
import VueRouter from 'vue-router';
(()=>{
console.log("Wow it actually works");
Vue.use(VueRouter);
const routes = [
{
path: '/',
component: Viewport
}
];
const router = new VueRouter({
mode: "history",
routes: routes
});
window.app = new Vue({ router });
window.app.$mount('#jg-app');
})();
<script src="ui.js" type="module"> </script>
The problem is when I run this I get...
Uncaught TypeError: Failed to resolve module specifier "vue". Relative references must start with either "/", "./", or "../".
This leads me to believe I need a "fat" js that includes dependencies.
I also want to keep everything in es6 modules and avoid introducing say babel.
Is there a way to do this using rollup?
Update
Tried this...
import Vue from "./vue";
But then I get...
Error: Could not resolve './vue' from src/index.js
As far as I can tell this is not possible. I instead had to move the import from the ui project to the server project and create a static js file that looked like this...
//client
import Vue from "./vue"
let app = new Vue(...);
app.$mount('#jg-app');
and import the esm.browser version
// server
app.use('/vue', express.static(__dirname + '/node_modules/vue/dist/vue.esm.browser.js'));
// template
script(src="/main.js" type="module")
Now Vue is working, however, dependencies like Vue-Router appear to not have this es.browser style file.
This is not a solution, it's a workaround
The below rollup config is not esm, it's just a way to create a bundle with dependencies included.
You get one minified browser-compatible JS file.
Here's my working example rollup.config.js (you should replace input: 'src/index.js' with your web app entry point and output.file with a location for the generated bundle):
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import builtins from 'rollup-plugin-node-builtins';
import babel from 'rollup-plugin-babel';
import visualizer from 'rollup-plugin-visualizer';
import { terser } from "rollup-plugin-terser";
const browserPlugins = [
resolve({browser: true}), // so Rollup can properly resolve cuid
babel({
exclude: 'node_modules/**',
babelrc: false,
presets: ['es2015-rollup'],
}),
// builtins(),
commonjs(),
visualizer(),
terser(),
]
export default [
// browser-friendly UMD build
{
// external: Object.keys(globals),
input: 'src/index.js',
output: {
name: 'thinflux',
file: './dist/browser/thinflux.min.js',
format: 'umd'
},
plugins: browserPlugins,
}
];
One more thing: express should statically serve the output.file path, not your source files

Configuring app's basename in react-router

I'm struggling a bit with react-router 2.x configuration, specifically app basename.
I've an application which may have different base root throughout its lifecycle. For instance:
/ in development
/users in production
/account in production after migration
The basename comes into play in several places:
static asset compilation in Webpack
react-router main configuration
specifying redirect routes in redux actions
providing something like redirectUrl to API calls
My current solution is to have an ENV variable and make it available both to Webpack and to the app itself by injecting window.defs via an Express server, but I still end up having things like ${defs.APP_BASENAME}/signin in way too many places throughout the app.
How can I abstract the app base, or at least tuck it away in a single location? I should be able to specify the base route in Router's config, and then simply use relative routes somehow, right? Or am I missing something?
You can decorate your history with a basename. You could mix this with a DefinePlugin in your Webpack configuration to specify which basename should be used.
// webpack.config.js
new Webpack.DefinePlugin({
BASENAME: '/users'
})
// somewhere in your application
import { useRouterHistory } from 'react-router'
import { createHistory } from 'history'
const history = useRouterHistory(createHistory)({
basename: BASENAME
})
Given the basename: /users, React Router will ignore the /users at the beginning of the pathname so:
The URL /users is internally matched by the path /
The URL /users/profile matches the path /profile.
Similarly, you do not have to append the basename to the path when you are navigating within your application.
<Link to='/friends'>Friends</Link> will navigate to /friends internally, but the URL in the location bar will be /users/friends.
Today I ran into the same issue:
On my localhost I let an NGINX serve the stuff in the root context, but on my prod server, an Apache serves the stuff from a subdirectory...
Inspired by the answer from Paul S and inspired by the infos here:
https://github.com/ReactTraining/react-router/issues/353
I got the for me working solution:
In the Webpack config file I defined a plugin for my localhost dev env:
plugins: [
new webpack.DefinePlugin({
BASENAME: JSON.stringify("/")
})
],
In the Webpack PROD config file I defined a plugin for my prod env in a subfolder, i.e. www.example.com/users:
plugins: [
new webpack.DefinePlugin({
BASENAME: JSON.stringify("/users/")
}),
And in my react-router definitions I just reference:
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import { useBasename } from 'history'
...
<Router history={useBasename(() => browserHistory)({ basename: BASENAME })}>
For me a very elegant solution and easy too. It just cost me around five hours of looking around :-)
In React Router V6.
Edit package.json and add homepage : Directory name key value as follows
"homepage" : "https://blog.sangw.in/react-student-management",
OR
"homepage" : "/react-student-management",
and on Routers BrowserRouter add basename : Directory name as follows
<BrowserRouter basename={'/react-student-management'}>
and you are done.
Visit https://blog.sangw.in/react-student-management and app will be deployed and working.
Try this it will work
import { createBrowserHistory } from 'history';
const history = createBrowserHistory({
basename: 'base-name'
})
<Router history={history}>
</Router>