Static font files not served in Vite dev environnement - laravel

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.

Related

Configure SASS Load Path in Nuxt 3

I have my SCSS partials in my Nuxt 3 project's assets/css directory (e.g. assets/css/_cards.scss). I can import them in my components using the full path (#use '~/assets/css/cards';), but I'm having trouble getting the load path working so that I can import like #use 'cards';
From what I've seen, the Nuxt config should look like this to enable that, but this and similar variations are not working for me.
export default defineNuxtConfig({
vite: {
css: {
preprocessorOptions: {
scss: {
loadPaths: ['#/assets/css'],
},
},
},
},
});
This approach is not working for me either. However, my use case is that I wanted some global styles imported, as opposed to every component on its own.
What worked for me was to use css property directly inside defineNuxtConfig object.
export default defineNuxtConfig({
css: ["#/assets/css/_variables.scss"]
});
The correct key to use is includePaths which is documented here. I tried this key before, but the reason it did not work was that I used #/assets/css for the path. The # alias does not work in this option, so I needed to use ./assets/css for the path. Here is the corrected config:
export default defineNuxtConfig({
vite: {
css: {
preprocessorOptions: {
scss: {
includePaths: ['./assets/css'],
},
},
},
},
});

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

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

Getting svelte-material-ui working with snowpack and sass

I'm trying to get svelte material UI working with snowpack.
I have installed Snowpack and Snowpacks svelte template like so:
npm install --save-dev snowpack#next
npx create-snowpack-app xpapp --template #snowpack/app-template-svelte
This works, the sample svelte page shows up. Next I followed the Svelte Material UI instructions to "bundle this in your own code" as cited on the Usage chapter in the instructions here: https://github.com/hperrin/svelte-material-ui#usage
So I installed Sass and configured it in my snowpack.config.json file like this:
{
"extends": "#snowpack/app-scripts-svelte",
"scripts": {
"build:scss": "sass"
},
"devOptions": {},
"installOptions": {}
}
I followed the (very concise) instructions here: https://www.snowpack.dev/#sass
I've also added an empty src/theme/_smui-theme.scss file to my source files as the instructions say, and I installed the nessecary #smui components.
The problem is that I'm currently getting this error when starting the snowpack dev server:
> snowpack dev
Snowpack Dev Server (Beta)
NOTE: Still experimental, default behavior may change.
Starting up...
⠙ snowpack installing... #smui/icon-button, #smui/top-app-bar, svelte/internal
✘ /home/erik/Projects/svelte-xpapp/xpapp/node_modules/#smui/icon-button/_index.scss
Error: Unexpected character '#' (Note that you need plugins to import files that are not JavaScript)
at error (/home/erik/Projects/svelte-xpapp/xpapp/node_modules/snowpack/node_modules/rollup/dist/shared/rollup.js:161:30)
at Module.error (/home/erik/Projects/svelte-xpapp/xpapp/node_modules/snowpack/node_modules/rollup/dist/shared/rollup.js:15120:16)
at tryParse (/home/erik/Projects/svelte-xpapp/xpapp/node_modules/snowpack/node_modules/rollup/dist/shared/rollup.js:15009:23)
at Module.setSource (/home/erik/Projects/svelte-xpapp/xpapp/node_modules/snowpack/node_modules/rollup/dist/shared/rollup.js:15410:30)
at ModuleLoader.addModuleSource (/home/erik/Projects/svelte-xpapp/xpapp/node_modules/snowpack/node_modules/rollup/dist/shared/rollup.js:17460:20)
at async ModuleLoader.fetchModule (/home/erik/Projects/svelte-xpapp/xpapp/node_modules/snowpack/node_modules/rollup/dist/shared/rollup.js:17521:9)
at async /home/erik/Projects/svelte-xpapp/xpapp/node_modules/snowpack/node_modules/rollup/dist/shared/rollup.js:17491:36
at async Promise.all (index 0)
at async ModuleLoader.fetchModule (/home/erik/Projects/svelte-xpapp/xpapp/node_modules/snowpack/node_modules/rollup/dist/shared/rollup.js:17522:9)
at async Promise.all (index 0)
It seems that the #import statements in Material UI's _index.scss aren't recognized. I figure Snowpack should interpret/transpile .scss files, but it doesn't seem to be doing that.
So I came across the same problem using Svite as well as Snowpack. I was able to use the bare implementation:
// component.svelte <script>
import Button, { Label } from '#smui/button/bare'
import '#smui/button/bare.css'
That's all that's required with Svite.
With Snowpack, I needed to add rollup-plugin-svelte and update snowpack.config.js
// snowpack.config.js
module.exports = {
// ...
installOptions: {
rollup: { plugins: [require('rollup-plugin-svelte')()] }
},
// ...
}
I got it working with these install options:
installOptions: {
rollup: {
plugins: [
require("rollup-plugin-svelte")({
include: ["./node_modules"],
}),
require("rollup-plugin-postcss")({
use: [
[
"sass",
{
includePaths: ["./src/theme", "./node_modules"],
},
],
],
}),
],
},
},
Unfortunately, you'll have to run npx snowpack dev --reload for changes to the theme to take effect.
This won't extract css into .css files.
I also got an error message with the Dialog component during a production build.
Here is a full example: https://github.com/LeanderG/svelte-smui

How to load csv files into a nuxt vue component

I am currently trying to load a csv file into a Nuxt page. The folder structure is below and produces the error "Failed to load resource: the server responded with a status of 404 (Not Found)":
Project
|
+--pages
|
+--lesson
|
+--index.vue
+--file.csv
import * as d3 from 'd3';
export default{
data(){
return{
dataset1:[]
}
mounted(){
d3.csv('file.csv', (myData) => {
console.log('Mydta', myData);
this.dataset1 = myData;
})
}
}
I have added the following to the web pack config in the nuxt-folder:
build: {
/*
** You can extend webpack config here
*/
extend(config, ctx) {
config = {
module: {
rules: [
{
test: /\.csv$/,
loader: 'csv-loader',
options: {
dynamicTyping: true,
header: true,
skipEmptyLines: true
}
}
]
}
}
}
}
Thanks in advance
I recently had the same question and ended up using the #nuxt/content module – worked like a charm, didn't even need to include d3 (which is usually my go-to for parsing CSV files).
I believe the issue is you cannot access the csv file the way you are attempting to, the way to do that would be storing the file in the '/assets' directory which you can then access as shown in the docs I linked ~/assets/file.csv I think this is also a more correct location for storing such files to avoid having lingering files throughout the project
This worked for me:
async mounted() {
const d = await d3.csv("/data.csv");
console.log(d);
}
With data.csv placed in public folder.

Getting Babel 6 to work with IE8 (via. Gulp/Webpack)

I've got Babel 6 working nicely with Gulp and Webpack. I now need to polyfill it to get IE8 support.
I've installed the babel-polyfill, but can't get it working and the docs and Google haven't helped so far.
My Gulp task (inc. Webpack config):
gulp.task('webpack', function(callback) {
var webpackConfig = {
context: __dirname + '../../../js',
entry: {
homepage: [
'babel-polyfill',
'./public/homepage/homepage.js'
]
},
output: {
path: __dirname + '../../../dist/public/scripts/',
filename: '[name].bundle.js'
},
module: {
loaders: [
{
loader: 'babel-loader',
test: /\.js$/, // Only run .js files through Babel
include: /js/, // Only include the /js dir
query: {
//plugins: ['transform-runtime'], // Disabled pending fix to https://github.com/babel/babel/issues/2954
presets: ['es2015'],//, 'stage-0'
}
}
]
}
};
webpack(webpackConfig, function(err, stats) {
if (err) {
throw new gutil.PluginError('webpack', err);
}
gutil.log('[webpack]', stats.toString({
// output options
}));
callback();
});
});
From the docs (https://babeljs.io/docs/usage/polyfill/):
Usage in Node / Browserify / Webpack
To include the polyfill you need to require it at the top of the entry point to > your application.
require("babel-polyfill");
Usage in Browser
Available from the dist/polyfill.js file within a babel-polyfill npm release. This needs to be included before all your compiled Babel code. You can either prepend it to your compiled code or include it in a before it.
NOTE: Do not require this via browserify etc, use babel-polyfill.
I've tried simply adding the polyfill.js file to the top of the page, but IE8 still isn't happy with the compiled code's use of the default keyword.
I've also tried adding the polyfill to the webpack process, as per http://jamesknelson.com/using-es6-in-the-browser-with-babel-6-and-webpack/ and other suggestions from Google
What am I doing wrong?

Resources