Vite does not build my #extend rules from bulma-scss - sass

I'm having a build issue with the scss at-rule "extend" using Vite to build out a Vue3 component library using the bulma-scss NPM package.
Using Bluma buttons for example, I would like to import the bulma-scss button.scss file into my tag in my .vue file (or into the button.scss file and then import that into the script tag) like so:
<template/>
<script/>
...
<style lang="scss">
#import 'bulma-scss/elements/button';
</style>
When running $ vite build I get this error from Vite:
File: /Users/my-user/sites/component-library/node_modules/bulma-scss/elements/_button.scss
Error: The target selector was not found.
Use "#extend %control !optional" to avoid this error.
It is specifically this line in the bulma-scss package that it doesn't like (in this example) https://github.com/j1mc/bulma-scss/blob/master/elements/_button.scss#L71
it looks like I can get around this by adding the following preprocessor option to my storybook's vite configs:
css: {
preprocessorOptions: {
scss: {
additionalData: `#import "bulma-scss";`
}
},
},
But that would include the entirety of bulma-scss right? Ideally I would only import the things I need from bulma.
And here is my entire vite config file (sans the css preprocessorOptions)
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
import {resolve} from 'path';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
build: {
lib: {
entry: resolve(__dirname, 'src/index.js'),
name: 'lmsComponentLibrary',
},
rollupOptions: {
// make sure to externalize deps that shouldn't be bundled
// into your library
external: ['vue'],
output: {
// Provide global variables to use in the UMD build
// for externalized deps
globals: {
vue: 'Vue',
},
},
},
},
resolve: {
alias: {
'bulma-scss/': require('path').join(__dirname, 'node_modules/bulma-scss/'),
}
},
});

I think the problem comes from the bulma-scss package itself. In the file that you are importing there is no %control placeholder. Even its import ../utilities/controls and ../utilities/mixins don't have that placeholder neither. So the error is expected here.
The %control is defined in bulma-scss/utilities/extends so you can fix the problem by importing that file. BUT, it will lead to another problem because in the _extends.scss there are some variables that are not defined. So you need to import all the file that contains these variables.
Luckily, the package has a file containing all the utility variables. So you just need to import it.
#import 'bulma-scss/utilities/all'; <-- Add this line
#import 'bulma-scss/elements/button';

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 can I use fontawesome icons in a laravel application using vite?

I have installed #fortawesome/fontawesome-free package using npm. The latest Laravel application uses vite by default. I am unable to solve this issue. Any help would be much appreciated. My vite.config.js is
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import { viteStaticCopy } from 'vite-plugin-static-copy';
export default defineConfig({
plugins: [
laravel([
'resources/css/app.css',
'resources/js/app.js',
'resources/admin/css/app.css',
'resources/admin/js/app.js',
'resources/css/glide.css',
'resources/js/glide.js',
'resources/js/Sortable.js',
'resources/js/tinymce.js',
'resources/sass/app.scss',
'resources/admin/sass/app.scss',
]),
{
name: 'blade',
handleHotUpdate({ file, server }) {
if (file.endsWith('.blade.php')) {
server.ws.send({
type: 'full-reload',
path: '*',
});
}
},
},
viteStaticCopy({
targets: [
{
src: 'node_modules/#fortawesome/fontawesome-free/webfonts',
dest: '',
},
],
}),
],
});
I imported fontawesome scss files in app.scss. My app.scss file contains
#import "#fortawesome/fontawesome-free/scss/fontawesome";
#import "#fortawesome/fontawesome-free/scss/brands";
#import "#fortawesome/fontawesome-free/scss/regular";
#import "#fortawesome/fontawesome-free/scss/solid";
#import "#fortawesome/fontawesome-free/scss/v4-shims";
I tried using a third party library https://github.com/sapphi-red/vite-plugin-static-copy to copy webfonts of fontawesome package. Is there a better way than this?
I solved it by first installing sass pre-processor:
npm install -D sass
after that I imported all fontawesome scss files into my app.js file:
import './bootstrap';
import '#fortawesome/fontawesome-free/scss/fontawesome.scss';
import '#fortawesome/fontawesome-free/scss/brands.scss';
import '#fortawesome/fontawesome-free/scss/regular.scss';
import '#fortawesome/fontawesome-free/scss/solid.scss';
import '#fortawesome/fontawesome-free/scss/v4-shims.scss';
import Alpine from 'alpinejs';
window.Alpine = Alpine;
Alpine.start();
It is quite easy if you are not adding it via npm. Copy entire fontawesome dir into resources dir (/resources/fontawesome), then declare variable in your scss file like (assuming you are doing it in a file inside /resources/sass:
$fa-font-path: '../fontawesome/webfonts';
and import fontawesome files:
#import '../fontawesome/scss/brands';
#import '../fontawesome/scss/solid';
#import '../fontawesome/scss/light';
#import '../fontawesome/scss/fontawesome';
Build script will copy files to your /public/build/assets dir and change urls and dev script will load them from your resources dir.

Disable asset handling in Vite

I have a PHP project (WordPress theme) with Vite and PostCSS to bundle my JS and CSS files.
The output directory is build and everything worked, but as soon as I import fonts or images in my CSS, Vite copies them into the build folder and changes the paths in the source.
File structure:
styles
|- tailwind.css
|- fonts
|- fa-brands-400.eot
|- fa-brands-400.woff
|- fa-brands-400.woff2
|- fa-brands-400.svg
|- fa-brands-400.ttf
js
|- index.js
vite.config.js
...
In my tailwind.css, I'm importing the font:
#font-face{
font-family:"Font Awesome 5 Brands";
font-style:normal;
font-weight:400;
font-display:block;
src:url(../styles/fonts/font_awesome/fa-brands-400.eot);
src:url(../styles/fonts/font_awesome/fa-brands-400.eot?#iefix) format("embedded-opentype"),url( ../styles/fonts/font_awesome/fa-brands-400.woff2) format("woff2"),url(../styles/fonts/font_awesome/fa-brands-400.woff) format("woff"),url(../styles/fonts/font_awesome/fa-brands-400.ttf) format("truetype"),url(../styles/fonts/font_awesome/fa-brands-400 .svg#fontawesome) format("svg")
}
The problem, Vite copied the imported font files to my build folder and my font import now looks like this (in build/tailwind.css:
#font-face{
font-family:"Font Awesome 5 Brands";
font-style:normal;
font-weight:400;
font-display:block;
src:url(/fa-brands-400.eot);
src:url(/fa-brands-400.eot?#iefix) format("embedded-opentype"),url(/fa-brands-400.woff2) format("woff2"),url(/fa-brands-400.woff) format("woff"),url(/fa-brands-400.ttf) format("truetype"),url(/fa-brands-400.svg#fontawesome) format("svg")
}
Is there a way to disable this? I just want Vite to bundle my JS and CSS, but don't include my assets.
My vite.config.js looks like this:
import postcssImport from "postcss-import"
import tailwindcssNesting from "tailwindcss/nesting"
import tailwindcss from "tailwindcss"
import autoprefixer from "autoprefixer"
import postcssScss from "postcss-scss"
import { defineConfig } from "vite"
export default defineConfig({
build: {
outDir: "build",
cssCodeSplit: true,
emptyOutDir: true,
minify: false,
assetsDir: "",
rollupOptions: {
input: {
index: "js/index.js",
tailwind: "styles/tailwind.css",
},
output: {
entryFileNames: "[name].js",
assetFileNames: "[name].[ext]",
},
},
},
css: {
postcss: {
syntax: postcssScss,
plugins: [postcssImport, tailwindcssNesting, tailwindcss, autoprefixer],
},
},
clearScreen: true,
publicDir: false,
})
I am facing a similar issue with a library build. I want to have an image relative to my css file, but default it is placed at the root and the reference in the css file is also to the root (just like in your problem). I did not find a perfect solution, but I was able to place the image in the same folder as the css file, where the css file also references the image in the same folder. I used the rollup config option output.assetFileNames for this. You can pass your own function and in that function you can add the complete path to the folder where you want to add the asset.
assetFileNames: (assetInfo: PreRenderedAsset): string => {
if (assetInfo.type === 'asset') {
return 'styles/fonts/[name][extname]';
}
else {
return '[name][extname]';
}
},
This will place the fonts in the build/styles/font folder. The references in the css will also be in this folder.
There is one caveat: The references will begin with '/', so they will be from the root of the domain. I have not found a solution for this.

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

Loading D3 with Nuxt/Vue

I am trying to implement D3 in an app I am building with Nuxt. I have successfully imported it into a view in the <script> section with import * as d3 from 'd3' however because the app is being rendered server-side D3's functionality doesn't work (i.e. d3.select(...)) due to the lack of browser. In the Nuxt plugin documentation it suggests a pattern for client-only external plugins:
module.exports = {
plugins: [
{ src: '~plugins/vue-notifications', ssr: false }
]
}
I attempted to implement the pattern in the nuxt.config.js of my project:
module.exports = {
head: {
title: 'My Demo App',
meta: [...],
link: [...]
},
loading: {...},
plugins: [
{ src: '~node_modules/d3/build/d3.js', ssr: false}
]
}
However D3 throws a ReferenceError while looking for document and Nuxt throws a SyntaxError in the console pointing to something in the plugins field of nuxt.config.js.
For reference, demo.vue:
<template>
<div class="demo-container"></div>
</template>
<script>
import * as d3 from 'd3';
d3.select('.demo-container');
</script>
Would someone be able to point to what I'm doing wrong?
For anyone coming to this page looking for a solution,
these suggestions from piyushchauhan2011 here on GitHub sent me in the right direction.
All I needed to do:
import d3 in my single-file component, and then
do any DOM manipulation with d3 only within mounted()
Before all this, I had to of course add d3 to my project with yarn add d3 (or npm install d3).
[Edit: removed link that no longer works. It wasn't that relevant anyway.]
I was getting an error:
Must use import to load ES Module: .../node_modules/d3/src/index.js require() of ES modules is not supported. require() of .../node_modules/d3/src/index.js from .../node_modules/vue-server-renderer/build.dev.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules. Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from .../node_modules/d3/package.json.
I solved it by reading this: https://github.com/nuxt/nuxt.js/issues/9223
which indicates you can add this to your nuxt.config.js file:
build: {
standalone: true,
}
This allowed the d3 import to work.
import * as d3 from "d3";
Here's a simple step-by-step tutorial:
Create a new NuxtJS project (Skip this step if you have an existing project)
npm init nuxt-app nuxtjs-d3js-example
Install D3JS
npm install d3
npm install #types/d3 --save-dev
Import D3JS and add a target
HTML:
<p id="d3-target"></p>
JavaScript:
import * as d3 from 'd3'
export default {
name: 'NuxtTutorial',
mounted: function() {
d3.select("#d3-target").text("This text is manipulated by d3.js")
},
}
Fix ES Module error (mentioned by #agm1984)
Error:
require() of ES Module /home/johnson/projects/nuxtjs-d3js-example/nuxtjs-d3js-example/node_modules/d3/src/index.js from /home/johnson/projects/nuxtjs-d3js-example/nuxtjs-d3js-example/node_modules/vue-server-renderer/build.dev.js not supported. Instead change the require of index.js in /home/johnson/projects/nuxtjs-d3js-example/nuxtjs-d3js-example/node_modules/vue-server-renderer/build.dev.js to a dynamic import() which is available in all CommonJS modules.
nuxt.config.js:
build: {
standalone: true,
}
A minimal project example can be found at: https://github.com/j3soon/nuxtjs-d3js-example, with each step detailed in the Git commit history.

Resources