How to detect Development mode within Svelte code? [duplicate] - debugging

The dev mode using npm run dev, the release mode using npm build
How could i know that it's currently built on dev mode or not in the code, for example:
<script>
import {onMount} from 'svelte';
onMount(function(){
if(DEVMODE) { // --> what's the correct one?
console.log('this is x.svelte');
}
})
</script>

If you are using sveltekit:
import { dev } from '$app/environment';
if (dev) {
//do in dev mode
}

Not sure about the correct method. I share what I did on my project.
in rollup.config.js
import replace from "#rollup/plugin-replace";
const production = !process.env.ROLLUP_WATCH;
inside plugins:[ ] block add this
replace({
isProduction: production,
}),
rollup.config.js will look like this.
},
plugins: [
replace({
isProduction: production,
}),
svelte({
Then use isProduction inside components .
if (!isProduction){ console.log('Developement Mode'); }

If you are using Svelte with Vite, you may use:
import.meta.env.DEV - true in development environment.
import.meta.env.PROD - true in production environment.
import.meta.env.MODE - name of the mode, if you need more control.
See Vite docs on Env variables

I solved this problem by checking the hostname the application is running on.
You can also use other forms like, port or even msm a localStore browser variable.
Note that I check if the application is running on the client side before using the 'window'
const isProduction = (): boolean => {
// Check if is client side
if (typeof window !== 'undefined' && window.document !== undefined) {
// check production hostname
if (window?.location.hostname !== undefined &&
window.location.hostname === 'YOUR_PRODUCTION_HOSTNAME') {
return true
} else {
return false
}
} else {
return false
}
}

When using Svelte (not svelte-kit), this worked for me inside svelte components:
<script>
let isProduction = import.meta.env.MODE === 'production';
if (!isProduction) {
console.log("Developement Mode");
} else {
console.log("Production Mode");
}
</script>
Thanks timdeschryver for the reference

Related

How can I see `cy.log` output when using Cypress headlessly?

When running Cypress headlessly, I can see console.log output from the frontend code under test by using the DEBUG environment variable, like:
DEBUG='cypress:launcher' npx cypress run --browser chrome
However, I haven't found any similar way to see the output of cy.log from the Cypress test code when running headlessly. Even with DEBUG='cypress:*' I don't see them - they only seem to be visible in the interactive interface. It feels like there must be some way to see the cy.log output headlessly - can someone help with that?
The first step is to add a new task in your Cypress config file so that you can run console.log from Node:
import { defineConfig } from "cypress";
export default defineConfig({
e2e: {
setupNodeEvents(on, config) {
on("task", {
log(args) {
console.log(...args);
return null;
}
});
},
},
});
Then, you can override cy.log so that it calls this task whenever you run the command in headless mode, and console.log when you're running in headed mode. You can do this by adding the following to your commands file:
Cypress.Commands.overwrite("log", function(log, ...args) {
if (Cypress.browser.isHeadless) {
return cy.task("log", args, { log: false }).then(() => {
return log(...args);
});
} else {
console.log(...args);
return log(...args);
}
});

Static font files not served in Vite dev environnement

I am trying to switch from webpack to vite in an existing Laravel application. For local development I use Laravel Valet.
If I run vite build everything works correctly (images, fonts, scss), but if I run vite the only bug I get is that it doesn't get the fonts path correctly (Error 404):
https://example.test:5173/fonts/open-sans/regular-400.woff2
Without the port it would work.
I've read a lot and I think I've tried everything:
Attempts (failed) in the Vite configuration:
export default defineConfig(({ command, mode }) => {
return {
// root: './',
// base: './',
// publicDir: 'public',
// assetsInclude: ['public/fonts'],
// Rest of the configuration are Plugins (Laravel, Vue), Alias etc...
}
});
So I try to change the root, base, publicDir nor assetsInclude and don't remember what else... and nothing of them hasn't solved my problem.
The structure of my public folder:
- public
- build
- assets
- fonts
- images
css font-face:
#font-face {
...
url('/fonts/open-sans/regular-400.woff2') format('woff2'),
url('/fonts/open-sans/regular-400.woff') format('woff');
}
The solution I found was to add the alias for the font path (public/font) only in the dev environment:
export default defineConfig(({ command, mode }) => {
const alias = {
(some alias),
};
// dev environment
if (command === 'serve') {
Object.assign(alias, { '/fonts': path.resolve(__dirname, 'public/fonts') });
}
return {
...
resolve: {
alias
}
}
});
I think it's a Vite bug and I don't know if that's the best solution for that, so I'm open to any suggestions.

How to run both svelte and go

I'm trying to make a website using svelte(front) and golang(backend).
My problem is when I run those in different terminal to test my app('npm go dev' for svelte, 'go run .' for go), they run in different port. Go in port 8080 and Svelte in port 50838. How can I solve this?
Using vite to proxy requests to your Go backend is probably the simplest method (I'm assuming you are using vite!).
To do this add something like the following to your vite.config.js:
const config = {
...,
server: {
proxy: {
'/api': {
target: 'http://127.0.0.1:8080/',
proxyTimeout: 10000
},
'/': { // Complex example that filters based on headers
target: 'http://127.0.0.1:8080/',
proxyTimeout: 600000,
bypass: (req, _res, _options) => {
let ct = req.headers['content-type'];
if (ct == null || !ct.includes('grpc')) {
return req.url; // bypass this proxy
}
}
}
},
}
};
This contains a few examples; you will need to tweak these to meet your needs.

Unresolved dependencies & Missing global variable name when trying to import #mapbox/mapbox-gl-geocoder

I'm beginning with Svelte and I would like to (more or less) reproduce Mapbox store locator tutorial with Svelte & rollup. (Starting from svelte REPL starter kit).
Everything's fine for loading a map and some markers, but as soon as I try to import this package https://github.com/mapbox/mapbox-gl-geocoder, nothing works anymore and I'm not familiar enough with Svelte to figure out how to setup rollup and fix it.
<script>
import { onMount, setContext } from 'svelte'
import mapbox from 'mapbox-gl/dist/mapbox-gl.js';
import MapboxGeocoder from '#mapbox/mapbox-gl-geocoder'; // <<--- Problem here
mapbox.accessToken = 'xxx';
let map;
let geocoder;
onMount(() => {
map = new mapbox.Map({,,,});
geocoder = new MapboxGeocoder({,,,});
});
</script>
terminal :
bundles src/main.js → public/build/bundle.js...
(!) Missing shims for Node.js built-ins
Creating a browser bundle that depends on 'events'. You might need to include https://github.com/ionic-team/rollup-plugin-node-polyfills
(!) Unresolved dependencies
https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency
events (imported by node_modules/#mapbox/mapbox-gl-geocoder/lib/index.js, events?commonjs-external)
(!) Missing global variable name
Use output.globals to specify browser global variable names corresponding to external modules
events (guessing 'events$1')
created public/build/bundle.js in 2s
browser console :
Uncaught ReferenceError: events$1 is not defined
at main.js:5
Then, I tried to add to my rollup config resolve and polyfills plugins, but have other errors.
rollup.config.js
import svelte from 'rollup-plugin-svelte';
import resolve from '#rollup/plugin-node-resolve';
import commonjs from '#rollup/plugin-commonjs';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
import preprocess from 'svelte-preprocess';
import nodeResolve from '#rollup/plugin-node-resolve';
import nodePolyfills from 'rollup-plugin-node-polyfills';
const production = !process.env.ROLLUP_WATCH;
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js'
},
plugins: [
nodeResolve(),
nodePolyfills(),
svelte({
// enable run-time checks when not in production
dev: !production,
// we'll extract any component CSS out into
// a separate file - better for performance
css: css => {
css.write('bundle.css');
},
preprocess: preprocess()
}),
// If you have external dependencies installed from
// npm, you'll most likely need these plugins. In
// some cases you'll need additional configuration -
// consult the documentation for details:
// https://github.com/rollup/plugins/tree/master/packages/commonjs
resolve({
browser: true,
dedupe: ['svelte']
}),
commonjs(),
// In dev mode, call `npm run start` once
// the bundle has been generated
!production && serve(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload('public'),
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser()
],
watch: {
clearScreen: false
}
};
function serve() {
let started = false;
return {
writeBundle() {
if (!started) {
started = true;
require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
stdio: ['ignore', 'inherit', 'inherit'],
shell: true
});
}
}
};
}
Gives me this
bundles src/main.js → public/build/bundle.js...
LiveReload enabled
(!) `this` has been rewritten to `undefined`
https://rollupjs.org/guide/en/#error-this-is-undefined
node_modules/base-64/base64.js
163: }
164:
165: }(this));
^
to conclude: I'm a bit lost :D
thanks in advance

ionic 2 caching images

I am writing an ionic 2 application, and want to cache images.
After long searching on the web I found these references:
https://gist.github.com/ozexpert/d95677e1fe044e6173ef59840c9c484e
https://github.com/chrisben/imgcache.js/blob/master/js/imgcache.js
I implemented the given solution, but i see that the ImgCache module does not behave as expected - the ImgCache.isCached callback is never called.
Any idea or other good solution for caching images in ionic 2?
======== UPDATE ==========
Here is the directive code I use:
import { Directive, ElementRef, Input } from '#angular/core';
import ImgCache from 'imgcache.js';
#Directive({
selector: '[image-cache]'
})
export class ImageCacheDirective {
constructor (
private el: ElementRef
) {
// init
}
ngOnInit() {
// This message is shown in console
console.log('ImageCacheDirective *** ngOnInit: ', this.el.nativeElement.src);
this.el.nativeElement.crossOrigin = "Anonymous"; // CORS enabling
ImgCache.isCached(this.el.nativeElement.src, (path: string, success: any) => {
// These message are never printed
console.log('path - '+ path);
console.log('success - '+ success);
if (success) {
// already cached
console.log('already cached so using cached');
ImgCache.useCachedFile(this.el.nativeElement);
} else {
// not there, need to cache the image
console.log('not there, need to cache the image - ' + this.el.nativeElement.src);
ImgCache.cacheFile(this.el.nativeElement.src, () => {
console.log('cached file');
// ImgCache.useCachedFile(el.nativeElement);
});
}
});
}
}
In app.nodule.es I do:
import { ImageCacheDirective } from '../components/image-cache-directive/image-cache-directive';
and then in home.html:
<img src="http://localhost/ionic-test/img/timeimg.php" image-cache>
It's late but probably this is the solution:
1. Install cordova FileTransfer:
ionic plugin add cordova-plugin-file-transfer --save
2. Init ImgCache when the deviceready event of cordova fires. In src/app/app.component.ts add these methods (or integrate them with your initializeApp() method - this method comes up with a default project start):
initImgCache() {
// activated debug mode
ImgCache.options.debug = true;
ImgCache.options.chromeQuota = 100 * 1024 * 1024; // 100 MB
ImgCache.init(() => { },
() => { console.log('ImgCache init: error! Check the log for errors'); });
}
initializeApp() {
this.platform.ready().then(() => {
this.initImgCache();
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
StatusBar.styleDefault();
Splashscreen.hide();
});
}
Another option is to use a dedicated cache manager for ionic. instead of implementing everything on your own.
Here are 2 options :
1. A generic cache implementation :https://github.com/Nodonisko/ionic-cache
2. This one is better for images: https://github.com/BenBBear/ionic-cache-src
EDIT:
This is not a "link only" answer.. it tells the user to use a ready made implementations instead of trying to implement from scratch.

Resources