VueJS ignoring global import - javascript

I'm trying to import a .less file in my App.vue so that its contents are available on all components.
I create the example app like this:
vue create less_test
then I install the less npm packages
cd less_test
npm install less less-loader --save-dev
I create this simple less file in src/
_variables.less
// Colors
#yellowish: #E19525;
Then on HelloWorld.vue I change the <style> to this:
<style lang="less" scoped>
.hello {
background-color: #yellowish;
}
...
</style>
And on App.vue to this:
<style lang="less">
#import "_variables.less";
...
</style>
But when I try to build, I get this error:
.hello {
background-color: #yellowish;
^
Variable #yellowish is undefined
How can I import the global .less file without having to import it on each component?

I just add a <style src="#/path/to/_variables.less" lang="scss"></style> in my App.vue.

Related

vue-multiselect styles working in dev but not in prod

I have added <style src="vue-multiselect/dist/vue-multiselect.min.css"> to my vue component, its styles working when running npm run dev but not when running npm run prod. How to fix that?
<template>
<multi-select :id="id" v-model="value" :options="options" :multiple="multiple" :max="max"></multi-select>
</template>
<script>
import multiSelect from 'vue-multiselect';
export default {
name: "my-multi-select",
components: { multiSelect },
}
</script>
<style src="vue-multiselect/dist/vue-multiselect.min.css"></style>
The problem is, that you using a relative path. What you need is to add a ref to your src folder, to tell vue-cli, that you want to include it in your production build.
<style>
#import './assets/styles/vue-multiselect.min.css';
</style>
The # refers your src path. Where you store it or what you call your folders is up to you.
EDIT: Another approach could be to reinstall the package with this command:
npm install vue-multiselect#next --save
Or just import it like you do with the component:
import Multiselect from 'vue-multiselect'
import 'vue-multiselect/dist/vue-multiselect.min.css'
EDIT 2: vue.config.js, create this file in your root. The content should be:
module.exports = {
publicPath: './'
};

Element UI icons wont show up using Laravel Mix

I made a simple website using Vue and Element UI. I used Laravel Mix to compile my code.
During development, the icons are showing up but when I run "npm run prod" and upload it to Github Pages they wont show up.
This is my webpack.mix.js
let mix = require('laravel-mix');
mix.js('src/js/app.js', 'public/')
.sass('src/styles/app.scss', 'public/')
.babelConfig({})
.disableNotifications();
I am using on demand components and followed this doc so my root vue file looks like this:
import Vue from 'vue'
import store from './vuex'
import router from './vue-router'
import Element from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import lang from 'element-ui/lib/locale/lang/es'
import locale from 'element-ui/lib/locale'
locale.use(lang)
Vue.use(Loading.directive);
Vue.component(Select.name, Select)
Vue.component(Option.name, Option)
Vue.component(Input.name, Input)
Vue.component(Icon.name, Icon)
new Vue({
el: '#app',
router,
store,
});
Following the same doc, I added a .babelrc file on my root directory but I didn't managed to get it working with the preset es2015 so I used #babel/preset-env instead. I dont actually know how to properly use Babel so the whole error might be over here but idk.
{
"presets": [["#babel/preset-env", { "modules": false }]],
"plugins": [
[
"component",
{
"libraryName": "element-ui",
"styleLibraryName": "theme-chalk"
}
]
]
}
I noticed something weird, when I run npm run prod, the output shows something like this:
The fonts folder and the needed fonts are being copied to my root directory, so when its on Github it makes a request to the root domain, the root folder, the right url should be over (I guess?) /h3lltronik.github.io/my-site/ but it is on /h3lltronik.github.io/.
Just in case is needed, Im using the icons like this:
<el-input v-model="search" prefix-icon="el-icon-search" class="filter_input element-input bordered" #input="onChangeSearch"
placeholder="Search for a country..."></el-input>
And this is my index.html
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>H3lltronik</title>
<link rel="stylesheet" href="./public/app.css">
</head>
<body>
<div id="app" :class="modeClass">
<transition name="el-fade-in">
<router-view class="content-body"></router-view>
</transition>
</div>
<script src="./public/app.js"></script>
</body>
</html>

How do I import files into a scoped style tag without it bleeding out?

I'm importing a css file in a style tag using a .vue file. The scoped css file is affecting all the css on my page and I only want it to affect my current component.
<template>
<div>
<router-view></router-view>
</div>
</template>
<style type="text/css" scoped>
#import '~bootstrap/dist/css/bootstrap.css';
</style>
How do I import a css file that is scoped to my current component?
Can you use sass?
First you'd have to install sass-loader:
npm install sass-loader node-sass --save-dev
Then you can use it like this:
<template>
<div class="container">
<router-view></router-view>
</div>
</template>
<style lang="scss" scoped>
.container {
#import '~bootstrap/dist/css/bootstrap.css';
}
</style>

Next.js - import css file does not work

I am creating a project with react, redux and next.js, and want to import CSS files in js.
I followed instructions in next.js/#css and next-css, but find out that CSS styles do not work.
My code is as follow:
pages/index.js:
import React from 'react'
import "../style.css"
class Index extends React.Component {
render() {
return (
<div className="example">Hello World!</div>
);
}
}
export default Index
next.config.js:
const withCSS = require('#zeit/next-css')
module.exports = withCSS()
style.css:
.example {
font-size: 50px;
color: blue;
}
package.json:
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"#zeit/next-css": "^0.1.5",
"next": "^6.0.0",
"react": "^16.3.2",
"react-dom": "^16.3.2",
"react-redux": "^5.0.7",
"react-scripts": "1.1.4",
"redux": "^4.0.0",
"redux-devtools": "^3.4.1"
},
"scripts": {
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject",
"dev": "next",
"build": "next build",
"start": "next start"
}
}
Questions:
1. There is an "Uncaught SyntaxError" in Chrome, but it seems to not affect the rendering of the page. But I still wondering the reason and the solution. index.js error in chrome is below img
2. As shown in Chrome, there's no "example" class, which means the style.css file is not loaded. Am I missing anything? no CSS file in chrome
Thanks in advance.
EDIT 2: As of Next.js > 10, you can import a global CSS file into _app.js, and you can use CSS modules in your components. More in the Next.js docs.
EDIT: As of Next.js 7, all you have to do to support importing .css files is to register the withCSS plugin in your next.config.js. Start by installing the plugin as dev dependency:
npm install --save-dev #zeit/next-css
Then create the next.config.js file in your project root and add the following to it:
// next.config.js
const withCSS = require('#zeit/next-css')
module.exports = withCSS({/* my next config */})
You can test that this is working by creating a simple page and importing some CSS. Start by creating a CSS file:
// ./index.css
div {
color: tomato;
}
Then create the pages folder with an index.js file. Then you can do stuff like this in your components:
// ./pages/index.js
import "../index.css"
export default () => <div>Welcome to next.js 7!</div>
You can also use CSS modules with a few lines of config. For more on this check out the documentation on nextjs.org/docs/#css.
Deprecated: Next.js < 7:
You'll also need to create a _document.js file in your pages folder and link to the compiled CSS file. Try it out with the following content:
// ./pages/_document.js
import Document, { Head, Main, NextScript } from 'next/document'
export default class MyDocument extends Document {
render() {
return (
<html>
<Head>
<link rel="stylesheet" href="/_next/static/style.css" />
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
)
}
}
The stylesheet is compiled to .next/static/style.css which means that the CSS file is served from /_next/static/style.css, which is the value of the href attribute in the link tag in the code above.
As for the first question, it's probably Chrome not understanding the import syntax. Try to enable the Experimental Web Platform flag in chrome:flags and see if that solves it.
For anyone who comes here ,the new Next JS supports CSS out of the box. The catch is that for modules (components), they must be named as the component. So, if you have a header inside a components directory, it must be named header.module.css
built-in-css-module-support-for-component-level-styles
Add {name}.css to src/static/styles/.
Then modify the Head in src/pages/_document.js to include the following link:
<Head>
<link href="/static/styles/{name}.css" rel="stylesheet">
</Head>
for next above 9.3, global css is written in "styles/globals.css" and you can import it to _app.js
import "../styles/globals.css";
Then for each component, you can write its own css and import it into the component. Pay attention to the naming:nameOfFile.module.css
Let's say you have "product.js" component and "product.module.css". you want to load css from "product.css" into "product.js"
import classes from "./product.module.css" // assuming it's in the same directory
you put all class names into product.module.css. Assume you have .main-product in product.module.css. Inside product.js, let's say you have a div to style
<div className={classes.main-product} > </div>
with the css module feature, you can use the same className in other components and it wont conflict. Because when next.js compiles, it will hash the name of the className, using its module. So hashed values of same classnames from different modules will be same
you need create to custom _document.js file.
Custom document when adding css will look like:
import React from "react";
import Document, { Head, Main, NextScript } from "next/document";
export default class MyDocument extends Document {
render() {
const { buildManifest } = this.props;
const { css } = buildManifest;
return (
<html lang="fa" dir="rtl">
<Head>
{css.map(file => (
<link rel="stylesheet" href={`/_next/${file}`} key={file} />
))}
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
);
}
}
As Zeit said :
Create a /static folder at the same level the /pages folder.
In that folder put your .css files
In your page components import Head and add a to your CSS.
import Head from 'next/head'
function IndexPage() {
return (
<div>
<Head>
<title>My page title</title>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
</Head>
<p>Hello world!</p>
</div>
)
}
export default IndexPage
And that's it, this way Next.js should render the link tag in the head of the page and the browser will download the CSS and apply it.
Thanks Sergiodxa at Github for this clear solution.
If you use next.js do this.
create next.config.js in root projects
const withCSS = require('#zeit/next-css');
function HACK_removeMinimizeOptionFromCssLoaders(config) {
console.warn(
'HACK: Removing `minimize` option from `css-loader` entries in Webpack config',
);
config.module.rules.forEach(rule => {
if (Array.isArray(rule.use)) {
rule.use.forEach(u => {
if (u.loader === 'css-loader' && u.options) {
delete u.options.minimize;
}
});
}
});
}
module.exports = withCSS({
webpack(config) {
HACK_removeMinimizeOptionFromCssLoaders(config);
return config;
},
});
Don't forget to restart the server
Global CSS Must Be in Your Custom <App>
Why This Error Occurred
An attempt to import Global CSS from a file other than pages/_app.js was made.
Global CSS cannot be used in files other than your Custom due to its side-effects and ordering problems.
Possible Ways to Fix It
Relocate all Global CSS imports to your pages/_app.js file.
Or, update your component to use local CSS (Component-Level CSS) via CSS Modules. This is the preferred approach.
Example:
// pages/_app.js
import '../styles.css'
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
Set this to false if your app works directly with the web 5 package.
module.exports = {
// Webpack 5 is enabled by default
// You can still use webpack 4 while upgrading to the latest version of
// Next.js by adding the "webpack5: false" flag
webpack5: false,
}
You can use webpack 4.
yarn add webpack#webpack-4

What is best way for including bootstrap.css to nuxt project?

This is a part of my nuxt.config.js file:
head: {
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
// load bootsttrap.css from CDN
//{ type: 'text/css', rel: 'stylesheet', href: '//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' },
]
},
css: [
// this line include bootstrap.css in each html file on generate
'bootstrap/dist/css/bootstrap.css',
'assets/main.css'
],
In this case bootstrap.css included in each html file on nuxt generate.
For resolve it I comment line 'bootstrap/dist/css/bootstrap.css' in css section and uncomment rel stylesheet line in link section.
After this bootstrap.css file loaded from CDN and not included in html files. So, I think it not is very well idea.
How copy bootstrap.css from 'node_modules/bootstrap/dist/...' to '~/assets' on build, and after this, load it from here?
Steps to include bootstrap.css into a nuxt project:
1 .Install bootstrap-vue
npm i bootstrap-vue
2.Create the file plugins/bootstrap-vue.js and in it type:
/* eslint-disable import/first */
import Vue from 'vue'
import BootstrapVue from 'bootstrap-vue'
Vue.use(BootstrapVue)
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
3.Add created plugin to nuxt.config.js:
plugins: [
'#/plugins/bootstrap-vue',
],
After these steps it should work and you can use bootstrap.
This is the simplest way I have found to include the regular Bootstrap version (not Bootstrap-Vue) in your Nuxt.js project. First, install Bootstrap from your Nuxt.js project directory (I'm using version 5.0.0-beta2):
npm install bootstrap
Then, in nuxt.config.js file, include Bootstrap's CSS and Javascript like this:
css: [
"~/node_modules/bootstrap/dist/css/bootstrap.min.css"
],
plugins: [
{ src: "~/node_modules/bootstrap/dist/js/bootstrap.bundle.min.js", mode: "client" }
],
Note the mode: "client" flag which indicates that the Javascript should only be run on the client. This prevents a ReferenceError: document is not defined error that happens because Bootstrap is not compatible with server side rendering.
For me the best way if you are using scss
As for me i create a sass directory inside assets directory in nuxt.
Then i add app.scss file inside sass directory i just created.
Then inside app.scss i import the following:
#import "bootstrap-variable-override";
#import "~bootstrap/scss/bootstrap.scss";
Then i do yarn add node-sass sass-loader --save
After that in nuxt.config.js i modify css array to include my app.scss
css: [
'#/assets/sass/app.scss'
],
This will compile whatever scss i will write and import in app.scss and provide as a compiled css.
But if you are bootstrap-vue then all you need to do is add this as modules:
modules: ['bootstrap-vue/nuxt']
Way to add Bootstrap 5 with nuxt.js:
If you don't want to do it manually by reading the following answer, you can simply clone my bootstrap 5 with nuxt boilerplate repository, click here.
Installation
npm install bootstrap#next
Note: The command will change, currently bootstrap 5 is in the beta version.
After installing the bootstrap, you will know that you need to install some loaders to compile Bootstrap.
npm install --save-dev sass sass-loader fibers postcss postcss-loader autoprefixer
Note: Installation of fibers is not mentioned in bootstrap documentation but synchronous compilation with sass (2x speed increase) is enabled automatically when fibers is installed.
Adding the CSS Part of Bootstrap and the Customized Bootstrap
At first, create a folder in your nuxt project’s assests folder and also create a scss file inside the created folder. Suppose, the folder’s name is bootstrap and the file name is ‘mystyle.scss’. Now, on this mystyle.scss file, you can override any built-in custom Bootstrap variables.
But you need to import bootstrap styles in this mystyle.scss too.After that, you need the following line to import bootstrap styles
#import "~bootstrap/scss/bootstrap";
Note: Make sure that you import this in the last line of your .scss file.
After importing the bootstrap style, you need to edit the nuxt.config.js
export default {
css: [ { src: '~/assets/bootstrap/mystyle.scss', lang: 'sass'}
],
}
This will not only compile the overridden bootstrap styles but also add the bootstrap style in the whole nuxt project.
Adding the Javascript Part of Bootstrap
First, download bootstrap. You will get a css and a js folder on that downloaded folder. There are many files under those two folders.
We just need one file from js folder. The name of that file is bootstrap.bundle.min.js. Copy that 'bootstrap.bundle.min.js' file and paste that file on your nuxt project's static folder. Then you need to edit your nuxt.config.js to use it.
export default {
script: [
{
src: '/bootstrap.bundle.min.js',
}
]
}
That's it, enjoy!
You can read about it in detail in my medium article, click here.
If you are looking to centralize your CSS imports (specifically bootstrap from node_modules, in your case) into a single file for Nuxt generating, you could include an at-rule import to your 'assets/main.css' (recommend to update it to '~/assets/main.css') specified in your config.
#import '../node_modules/bootstrap/dist/css/bootstrap.css'
Just a reminder: when you simply run Nuxt in dev mode, the CSS will be injected via JS. When generated, however, Nuxt will create a single, hashed, CSS file as part of the document root directory.
In my case, I put bootstrap.css file in "static" folder, and then register it to the nuxt.config.js as bellow
head: {
title: "Nuxt",
meta: [
{ charset: "utf-8" },
{ name: "viewport", content: "width=device-width, initial-scale=1" },
{
hid: "description",
name: "description",
content: "Nuxt"
}
],
link: [
{ rel: "icon", type: "image/x-icon", href: "/favicon.ico" },
{ rel: "stylesheet", href: "/css/bootstrap.css" } //Register your static asset
]
},
Here is my setup, and this is for those who like to customize bootstrap default style:
In my assets/styles/_bootstrap.scss I have imported required style:
#import "~bootstrap/scss/functions";
#import "~bootstrap/scss/variables";
#import "~bootstrap/scss/mixins";
//#import "~bootstrap/scss/root";
#import "~bootstrap/scss/reboot";
#import "~bootstrap/scss/type";
//#import "~bootstrap/scss/images";
//#import "~bootstrap/scss/code";
#import "~bootstrap/scss/grid";
//#import "~bootstrap/scss/tables";
#import "~bootstrap/scss/forms";
#import "~bootstrap/scss/buttons";
#import "~bootstrap/scss/transitions";
//#import "~bootstrap/scss/dropdown";
//#import "~bootstrap/scss/button-group";
//#import "~bootstrap/scss/input-group";
//#import "~bootstrap/scss/custom-forms";
//#import "~bootstrap/scss/nav";
//#import "~bootstrap/scss/navbar";
//#import "~bootstrap/scss/card";
//#import "~bootstrap/scss/breadcrumb";
//#import "~bootstrap/scss/pagination";
//#import "~bootstrap/scss/badge";
//#import "~bootstrap/scss/jumbotron";
//#import "~bootstrap/scss/alert";
//#import "~bootstrap/scss/progress";
//#import "~bootstrap/scss/media";
//#import "~bootstrap/scss/list-group";
#import "~bootstrap/scss/close";
#import "~bootstrap/scss/modal";
//#import "~bootstrap/scss/tooltip";
//#import "~bootstrap/scss/popover";
#import "~bootstrap/scss/carousel";
#import "~bootstrap/scss/utilities";
//#import "~bootstrap/scss/print";
Just in case you like to change the default style of bootstrap then I created assets/styles/_bootstrap-variables.scss:
There are lots of variable that you can find in node-modules/bootstrap/scss/variables.scss, I am just changing a few.
#import url('https://fonts.googleapis.com/css?family=Cabin:400,500,700');
$font-family-cabin: 'Cabin', sans-serif;
$font-family-base: $font-family-cabin;
$primary: #b62f20;
$secondary: #e8e8e9;
$success: #87b4a6;
$info: #f0f6fc;
//$warning: #faeecf;
//$danger: $red !default;
//$light: $gray-100 !default;
//$dark: $gray-800 !default;
And import all my other styles and plugins in one file assets/styles/main.scss:
#import "bootstrap-variables"; // this should alway be on top
#import "bootstrap";
#import "my-other-style";
And finally, import the stylesheet in layouts/default.vue
<template lang="pug">
div
nuxt
</template>
<style lang="scss">
#import '../assets/styles/main';
</style>
In my case, I add it from CDN as an object entry to link array (in nuxt.config.js)
link: [
{rel: 'stylesheet', type: 'text/css', href: 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css'}
]
You install bootstrap-vue :
yarn add bootstrap-vue
Then in the nuxt.config.js file you add a module, and a separate config for importing the icons :
modules: ['bootstrap-vue/nuxt'],
bootstrapVue: {
icons: true // Install the IconsPlugin (in addition to BootStrapVue plugin
}
And thats it.
For more configuration read the documentation here : https://bootstrap-vue.org/docs
(Read until the middle where it handles nuxt)
I used for Bootstrap v5
nuxt.config.js
css: [
'~/assets/scss/main.scss',
],
styleResources: {
scss: [
'~/node_modules/bootstrap/scss/_functions.scss',
'~/node_modules/bootstrap/scss/_variables.scss',
'~/node_modules/bootstrap/scss/_mixins.scss',
'~/node_modules/bootstrap/scss/_containers.scss',
'~/node_modules/bootstrap/scss/_grid.scss'
]
},
modules: [
'#nuxtjs/style-resources',
],
#nuxtjs/style-resources to have mixins, variables, grid available inside components:
https://www.npmjs.com/package/#nuxtjs/style-resources
example:
<style scoped lang="scss">
.header {
#include make-container();
}
</style>
main.scss
#import "bootstrap-configuration";
#import "bootstrap-optional";
#import "#/node_modules/bootstrap/scss/helpers";
#import "#/node_modules/bootstrap/scss/utilities/api";
#import "custom";
_bootstrap-configuration.scss
#import "bootstrap-required";
#import "#/node_modules/bootstrap/scss/utilities";
_bootstrap-optional.scss
(I can include only what I want)
#import "#/node_modules/bootstrap/scss/root";
#import "#/node_modules/bootstrap/scss/reboot";
#import "#/node_modules/bootstrap/scss/type";
#import "#/node_modules/bootstrap/scss/images";
#import "#/node_modules/bootstrap/scss/containers";
#import "#/node_modules/bootstrap/scss/grid";
#import "#/node_modules/bootstrap/scss/tables";
#import "#/node_modules/bootstrap/scss/forms";
#import "#/node_modules/bootstrap/scss/buttons";
#import "#/node_modules/bootstrap/scss/transitions";
#import "#/node_modules/bootstrap/scss/dropdown";
#import "#/node_modules/bootstrap/scss/button-group";
#import "#/node_modules/bootstrap/scss/nav";
#import "#/node_modules/bootstrap/scss/navbar";
#import "#/node_modules/bootstrap/scss/card";
#import "#/node_modules/bootstrap/scss/accordion";
#import "#/node_modules/bootstrap/scss/breadcrumb";
#import "#/node_modules/bootstrap/scss/pagination";
#import "#/node_modules/bootstrap/scss/badge";
#import "#/node_modules/bootstrap/scss/alert";
#import "#/node_modules/bootstrap/scss/progress";
#import "#/node_modules/bootstrap/scss/list-group";
#import "#/node_modules/bootstrap/scss/close";
#import "#/node_modules/bootstrap/scss/toasts";
#import "#/node_modules/bootstrap/scss/modal";
#import "#/node_modules/bootstrap/scss/tooltip";
#import "#/node_modules/bootstrap/scss/popover";
#import "#/node_modules/bootstrap/scss/carousel";
#import "#/node_modules/bootstrap/scss/spinners";
_custom.scss
(here I put variables to override Bootstrap and custom css for components)
$theme-colors: (
"red": #cf142b,
"black": #000,
"tan": #e0d9c7,
"blue": #009eba,
"blue-light": #d6e3e6,
"blue-dark": #006985,
"red-dark": #7d212b,
);
#import
'mixins/mixins';
#import
'_base/colors',
'_base/typography',
'_base/headings';
#import
'components/_page-header',
'components/text-editor',
'components/content-with-side-image',
'components/featured-artists',
'components/video-player',
'components/audio-player',
'components/call-to-action',
'components/divider',
'components/tabs',
'components/image-gallery',
'components/logos',
'components/button',
'components/page-submenu',
'components/page-submenu-target';
I got idea from
https://v5.getbootstrap.com/docs/5.0/customize/optimize/

Categories