Add all CSS files in a folder to nuxt.config - css

In my Nuxt project I have a folder assets/scss/globals/ with a lot of files which should be globally included.
Now in my nuxt.config file I can only include each file by manually like so:
// Global CSS: https://go.nuxtjs.dev/config-css
css: ['./assets/scss/globals/resets.scss'],
What I would need is something like this:
css: ['./assets/scss/globals/*.scss'],
But this doesn't work.
I have the styled-resources package installed as well for variable and mixin definition and there it works:
styleResources: {
scss: ['./assets/scss/variables/*.scss']
},
But the documentation clearly says to not include styles here:
Do not import actual styles. Use this module only to import variables, mixins, functions (et cetera) as they won't exist in the actual build. Importing actual styles will include them in every component and will also make your build/HMR magnitudes slower. Do not do this!
Is what I try to do any different from what the warning in styled-resources says?

CSS option in nuxt.config.js requires an array of files, If you do not want to specify them manually one by one you can simply create a function that returns them like below
Function in nuxt.config.js or import as a util
const styleFiles = (path) => {
const fs = require('fs')
const files = fs.readdirSync(path)
return files.map((i) => path + i)
}
Then use it like so
css: styleFiles('src/assets/scss/globals'),

Related

Gulpfile: How to compile each SCSS into separate CSS with same name but with additional common styles

First of all I'd like you guys to be gentle. I haven't been coding much in recent year and since gulp update when then changed syntax to writing functions and exporting I somehow made it work then and left with no changes up to this point, no clue if they changed something else. I've been happy with what it is right now, but I have no idea how to make it work the other way.
So anyway I'm working on a project right now, where there will be many htmls, and each one will have quite different styles, but some will be common. I want to make a main.scss file with common styles for each html, but I want to make a separate scss with styles specific to each html. This way in the end I want to have a separate css file made from a specific scss with same name combined with main.scss, so that it won't have to download a single large file, but only styles I need.
Example:
main.scss
01.scss
02.scss
03.scss
will compile to:
01.css ( main.scss + 01.scss )
02.css ( main.scss + 02.scss )
03.css ( main.scss + 03.scss )
This is my gulpfile right now:
const gulp = require('gulp');
const sass = require('gulp-sass');
const browserSync = require('browser-sync').create();
function style() {
return gulp.src('./scss/**/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./css'))
.pipe(browserSync.stream());
}
function watch() {
browserSync.init({
server: {
baseDir: './'
}
});
gulp.watch('./scss/**/*.scss', style);
gulp.watch('./*.html').on('change', browserSync.reload);
gulp.watch('./js/**/*.js').on('change', browserSync.reload);
}
exports.style = style;
exports.watch = watch;
If you have an idea how to do it in a better way I would really appreciate it.
I think you will have to import your main.scss into each of your other files and exclude main.scss from your gulp.src.
function style() {
return gulp.src(['./scss/**/*.scss', '!./scss/**/main.scss'])
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./css'))
.pipe(browserSync.stream());
}
'!./scss/**/main.scss' this negates or excludes that file from being passes into this task - I assumed main.scss was in the same folder as your other scss files, if that is not the case you will have to modify the path.
Then #import main.scss into each of your 01.scss, 02.scss, etc. files:
#import "main.scss"; // also assumes in same folder
You can put this import statement anywhere in the file, if it is first any of main.scss styles will be overridden by conflicting styles in the rest of the 0x.scss file. If you put the import statement at the end, then main.scss styles will override any previous conflicting styles.
Note: you should really be using #use instead of #import and gulp-dart-sass instead of gulp-sass at this point. See sass #use rule.
// in your gulpfile.js
const sass = require('gulp-dart-sass'); // once installed
#use "main.scss"; // must be at top of each scss file, such as 01.scss

Next.js Global CSS cannot be imported from files other than your Custom <App>

My React App was working fine, using global CSS also.
I ran npm i next-images, added an image, edited the next.config.js, ran npm run dev, and now I'm getting this message
Global CSS cannot be imported from files other than your Custom <App>. Please move all global CSS imports to pages/_app.js.
Read more: https://err.sh/next.js/css-global
I've checked the docs, but I find the instructions a little confusing as I am new to React.
Also, why would this error happen now? Do you think it has anything to do with the npm install?
I've tried to remove new files I've added along with their code, but this doesn't fix the problem. I've also tried what the Read more: suggests.
My highest tier component.
import Navbar from './Navbar';
import Head from 'next/head';
import '../global-styles/main.scss';
const Layout = (props) => (
<div>
<Head>
<title>Bitcoin Watcher</title>
</Head>
<Navbar />
<div className="marginsContainer">
{props.children}
</div>
</div>
);
export default Layout;
My next.config.js
// next.config.js
const withSass = require('#zeit/next-sass')
module.exports = withSass({
cssModules: true
})
My main.scss file
#import './fonts.scss';
#import './variables.scss';
#import './global.scss';
my global.scss
body {
margin: 0;
}
:global {
.marginsContainer {
width: 90%;
margin: auto;
}
}
The thing I find the weirdest is that this error came without changing anything to do with CSS, or Layout.js, and it was previously working?
I've moved my main.scss import to the pages/_app.js page, but the styles still aren't coming through. This is what the _app.js page looks like
import '../global-styles/main.scss'
export default function MyApp({ Component, props }) {
return <Component {...props} />
}
Use the built-in Next.js CSS loader (see here)
instead of legacy #zeit/next-sass.
Replace #zeit/next-sass package with sass.
Remove next.config.js. Or do not change CSS loading in it.
Move the global CSS as suggested in the error message.
Since Next.js 9.2 global CSS must be imported in Custom <App> component.
// pages/_app.js
import '../global-styles/main.scss'
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
To add styles only to a specific component or page you can use built-in support of CSS modules. (see here)
For example, if you have a component Button.js you can create a Sass file button.module.scss and include it in the component.
Next.js stops complaining when your file has module in naming, e.g., changing import '../global-styles/main.scss'; to import '../global-styles/main.module.scss'; would fix the warning and you could have your styles in the global-styles, or for example, in your component.
No extra dependencies/configurations in next.config.js is required.
You can replace the opinionated (and overly-complex?) NextJs CSS loaders with your own. Here's a simple one for global css:
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
reactStrictMode: true,
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
// Find and remove NextJS css rules.
const cssRulesIdx = config.module.rules.findIndex(r => r.oneOf)
if (cssRulesIdx === -1) {
throw new Error('Could not find NextJS CSS rule to overwrite.')
}
config.module.rules.splice(cssRulesIdx, 1)
// Add a simpler rule for global css anywhere.
config.plugins.push(
new MiniCssExtractPlugin({
experimentalUseImportModule: true,
filename: 'static/css/[contenthash].css',
chunkFilename: 'static/css/[contenthash].css',
})
)
config.module.rules.push({
test: /\.css$/i,
use: !isServer ? ['style-loader', 'css-loader'] : [MiniCssExtractPlugin.loader, 'css-loader'],
})
return config
},
}
Add this to your _app.js
import '../styles/globals.css'
For me the problem was because I had used two module.exports in my next.config.js file like this
const withPlugins = require('next-compose-plugins')
const sass = require('#zeit/next-sass')
const css = require('#zeit/next-css')
const nextConfig = {
webpack: function(config){
config.module.rules.push({
test: /\.(eot|woff|woff2|ttf|svg|png|jpg|gif)$/,
use: {
loader: 'url-loader',
options: {
limit: 100000,
name: '[name].[ext]'
}}
})
return config
}
}
module.exports = withPlugins([
[css],
[sass, {
cssModules: true
}]
], nextConfig)
module.exports = {
env: {
MONGO_URI = 'your uri'
}
}
. 1I modified it to change the export module like this.
const nextConfig = {
webpack: function(config){
config.module.rules.push({
test: /\.(eot|woff|woff2|ttf|svg|png|jpg|gif)$/,
use: {
loader: 'url-loader',
options: {
limit: 100000,
name: '[name].[ext]'
}}
})
return config
},
env: {
MONGO_URI: "your uri"
}
}
2then I deleted the second module.exports
This node package provides a perfect solution for it. You can find it here
Steps to fix it:
1. Add package:
npm install next-remove-imports
or
yarn add next-remove-imports
2. Add this wrapper variable inside your next.config.js
const removeImports = require('next-remove-imports')({
test: /node_modules([\s\S]*?)\.(tsx|ts|js|mjs|jsx)$/,
matchImports: "\\.(less|css|scss|sass|styl)$"
});
All it is doing is re-enabling global styling import rule for tsx|ts|js|mjs|jsx files
3. Wrap your next config export with this next-remove-imports wrapper. Something like this:
module.exports = removeImports((nextConfig)
4. Now restart your react app and you will be able to import CSS files inside any ts|js|js|jsx|mjs file or component.
Try to include ".module" in your scss file name.
Change main.scss to main.module.scss
Example:
import styles from './todolist-profile-info.module.scss'
You did not need to do anything inside of next.config.js.
Let's assume you are using a global css like Bootstrap, meaning it contains css that is meant to be applied to your entire application and all the different pages inside of it.
Global css files have to be wired up to NextJS in a very particular fashion.
So inside of the pages/ directory you need to create _app.js.
It's critical that the file be named _app.js.
Then at the top of that file you would import Bootstrap css in the following manner:
import 'bootstrap/dist/css/bootstrap.css';
Then you would add the following:
export default ({ Component, pageProps }) => {
return <Component {...pageProps} />;
};
So what is going on in that code?
Well, behind the scenes, whenever you try to navigate to some distinct page with NextJS, NextJS will import your component from one of the different files inside your pages/ directory.
NextJS does not just take your component and show it on the screen.
Instead it wraps it up inside of its own custom default component and that is referred to inside of NextJS as the App.
What you are doing by defining the _app.js is to define your own custom app component.
So whenever you try to visit a route inside a browser or your root route, NextJS is going to import that given component and pass it into the AppComponent as the Component prop.
So Component there is equal to whatever components you have in the pages/ directory. And then pageProps is going to be the set of components that you are intending to pass to your files inside of pages/.
So long story short, this thing is like thin wrapper around the component that you are trying to show on the screen.
Why do you have to define this at all?
Well, if you ever want to include some global css to the project, Bootstrap being a global css for example, you can only import global css into the _app.js file.
It turns out that if you try to visit other components or other pages, NextJS does not load up or even parse those files.
So any css you may have imported inside there will not be included in the final HTML file.
So you have a global css that must be included on every single page, it has to be imported into the app file because it's the only file that is guaranteed to be loaded up every single time a user goes to your application.
Don't forget that in addition to importing the css inside of _app.js, you also have to run an npm install bootstrap in your terminal.
You can read more on this here:
https://nextjs.org/docs/messages/css-global
For me, i got this error because I had used improper naming for my project's parent folder, had used special characters in it,
like project#1,
after removing special chars, and changing the folder name to like project-1, the error got away.
In my case there was typo in navbar.module.css
I've written navbar.moduile.css
you must for every component css/scss write navbar.module.css/scss/sass.Next js doesnt compile navbar.css/scss/sass. If hope my answer helps you !.

Webpack: Is there a way to replace imported file path before processing?

Setup: react, webpack, regular css and style loaders, nothing fancy
I want to be able to replace imported file on build step. Like if I build app with env WITH_THEME=true replace one css file with another with different name.
For example, I have 2 css files, style.css and style.theme.css, in react component I import only one file like this import './style.css' (I don't want to change this line, I know it is possible to make if condition with env var here).
So, if I start webpack with WITH_THEME=true I want it to actually import style.theme.css instead of regular style.css, but only if style.theme.css exists.
I came up with this solution, it is test condition for loader:
// ...
test: filePath => {
if (!/\.(s*)css$/.test(path.extname(filePath))) {
return false;
}
const { dir, name, ext } = path.parse(filePath);
const themeFilePath = `${dir}/${name}.theme${ext}`;
if (WITH_THEME && fs.existsSync(themeFilePath)) {
return false;
} else {
return true;
}
},
// ...
But with this way I need to import both style.css and style.theme.css in the component, so webpack could exlude one of them. Is there a better way to do this? Maybe there are some post-css solutions?
What I've actually ended up with:
I made webpack alias for theme-config file, which I import in every .(s)css file (#import '~scss-config';).
resolve: {
// ...
alias: {
'scss-config': path.resolve(
__dirname,
`./src/styles/config-${env.THEME || 'default'}.scss`
)
}
},
It allows to have multiple theme files, but you only need to import single config file, which got replaced with needed theme file in build step.

Best way to have global css in Vuejs

What is the best way to have a global css file in Vuejs for all components? (Default css like bg color, button styling, etc)
import a css file in the index.html
do #import in main component
put all the css in the main component (but that would be a huge file)
Import css in your index.html, but if you're using webpack you can just import your stylesheets in your main js config and all your components will get the css.
As comments below suggested if using webpack adding this to main.js works:
import './assets/css/main.css';
I found the best way is to create a new file in the assets folder, I created as global.css but you can name anything of your choice. Then, import this file global.css file in the main.js.
Note: Using this approach you can also create multiple files if you think the global.css is getting really large then simply import all those files in the main.js.
#\assets\global.css
/* move the buttons to the right */
.buttons-align-right {
justify-content: flex-end;
}
main.js
import Vue from 'vue'
import App from './App.vue'
import router from './routes'
Vue.config.productionTip = false
// Importing the global css file
import "#/assets/global.css"
new Vue({
router,
render: h => h(App)
}).$mount('#app')
In App.vue you can add a style property to declare you CSS file:
<style>
#import './assets/css/global.css';
</style>
You can also do something like this: https://css-tricks.com/how-to-import-a-sass-file-into-every-vue-component-in-an-app/
My folders are mostly structured like this:
- src
- assets
- _global.scss
- _colors.scss
- _fonts.scss
- _paragraphs
- index.scss // <-- import all other scss files.
This also works with normal css.
create a new css file in your assets folder for example : global.css
import "global.css" to main.js
import '#/assets/main.css';
There are to two ways, as I know, to achieve this.
Approach 1
Utilize vue.config.js configuration, less config can also be replaced with sass:
module.exports = {
css: {
loaderOptions: {
less: {
additionalData: `#import '#/style/common.less';`
}
}
}
}
Approach 2
In your .vue file, make your style looks like this:
<style lang="less">
#import (reference) "../../style/variables.less";
#app {
background: #bgColor;
}
</style>
Note: the (reference) flag is used to make variables defined in variables.less take effect. If you don't have variables, #import "../../style/variables.less"; is sufficient to do the trick.
For your reference, you can also take a look at this link:
https://github.com/tjcchen/vue-practice/tree/master/multipage-app
Sass announced their new module system. Why don't you use #use and #forward?
My approach is the best way to use scss with vite.
Use defineConfig to setup global scss (colors, mixin) and reuse in all component without import
css: {
preprocessorOptions: {
scss: {
additionalData: `#use "~/styles/main.scss" as *;`,
},
},
},
Here: code sandbox
create a vue.config.js file in your root directory
Create a styles folder inside your src folder and you can create your global style file here for example base.scss
to use scss install two dependencies
npm install node-loader sass-loader
Inside your vue.config.js paste code from below
module.exports = {
css: {
loaderOptions: {
sass: {
additionalData: `#import "#/styles/base.scss";`
}
}
}
};

How do I use LESS variables in my local package?

I made a local package to handle the browser implementation of our app.
Package.onUse(function(api) {
api.versionsFrom('1.2.1');
api.use('angular');
api.use('twbs:bootstrap', 'web.browser');
//.... some lines skipped
api.addFiles([
'styles/variables.less',
'styles/forms.less'
], 'web.browser');
});
In variables.less I have one variable declaration: #gray-light: #E6E6E6;, and in forms.less I have a style declaration that uses the variable. However when I try and compile the app I get the following error:
While processing files with less (for target web.browser):
packages/app-name-browser/styles/forms.less:6:22: variable #gray-light is undefined
I don't have the problem when I include the declaration in the same file, so I'm assuming the problem is that variables.less is being loaded after forms.less. Any way I can remedy this?
You can do something like:
Package.onUse(function(api) {
api.versionsFrom('1.2.1');
api.use('angular');
api.use('twbs:bootstrap', 'web.browser');
//.... some lines skipped
api.addFiles([
'styles/variables.less',
'styles/forms.less'
], 'client', {isImport: true});
});
And then in you main .less file you can import these files by
#import '{your-package:name}/styles/variables.less';
#import '{your-package:name}/styles/forms.less';

Resources