nuxt.js add css file - vue.js

I've created nuxt project
vue init nuxt/starter <project-name>
In my nuxt.config.js I added this:
css: [
{ src: '~assets/css/style.css', lang: 'css' }
]
and in my assets/css folder I have style.css
with
body {
background: black!important;
}
But nothing happens with no errors on console. what to I do?

you must add to nuxt.config.js
build: {
extractCSS: true
}
For example,
css: [
{ src: '~assets/css/style.css', lang: 'css' }
],
build: {
extractCSS: true
}
And use nuxt v0.10.6

Related

Webpack control of output css file names

I'm trying to control the filenaming of files produced from a Vue app with Webpack.
The environment where I want to host the built app doesn't like filenames with '.' (don't ask).
I have been able via get js files to comply with a 'hyphen' naming scheme by using output.filename in vue.config.js configureWebpack entry. But css files are not renamed.
As I am loading the two bulk packed files rather than chunks I can obviously manually rename the single css file. However when I run it I get an error
Error: Loading CSS chunk error failed.
(/my-path/resources/css/error.d0f9a634.css)
I'm hoping I can force all css files (including the error one) to be renamed by the build process.
My vue.config.js
module.exports = {
outputDir: path.resolve(__dirname, 'dist'),
publicPath: "/my-path/resources",
configureWebpack: {
optimization: {
splitChunks: false
},
output: {
filename: "[name]-js",
chunkFilename: "[name]-chunk-js",
// get cssFilename() {
// return "[name]-css";
// }
},
resolve: {
alias: {
'vue$': path.resolve('./node_modules/vue/dist/vue.common.js'),
},
},
},
// https://cli.vuejs.org/config/#productionsourcemap
productionSourceMap: false,
// https://cli.vuejs.org/config/#css-extract
css: {
extract: { ignoreOrder: true },
loaderOptions: {
sass: {
prependData: '#import \'~#/assets/scss/vuetify/variables\''
},
scss: {
prependData: '#import \'~#/assets/scss/vuetify/variables\';'
}
}
},
// ...
}
I have started to look at MiniCssExtractPlugin but not sure if that is the right direction to look. Any help appreciated.
I found a working solution for this via the css.extract element in vue.config.js.
configureWebpack: {
optimization: {
splitChunks: false
},
output: {
filename: "js/[name]-js",
chunkFilename: "js/[name]-chunk-js",
},
...
},
// https://cli.vuejs.org/config/#css-extract
css: {
extract: {
ignoreOrder: true,
filename: 'css/[name]-css',
chunkFilename: 'css/[name]-chunk-css',
},
loaderOptions: {
sass: {
prependData: '#import \'~#/assets/scss/vuetify/variables\''
},
scss: {
prependData: '#import \'~#/assets/scss/vuetify/variables\';'
}
}
},
...
Which as the documentation link for css.extract says
Instead of a true, you can also pass an object of options for the
mini-css-extract-plugin if you want to further configure what this
plugin does exactly
and is covered by the webpack mini-css-extract-plugin documentation

Can't compile sass while using Vue Storybook

I'm trying to create storybook on vue. My components written using sass. So, I made this in .storybook/main.js:
webpackFinal: (config) => {
config.module.rules.push({
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
'style-loader',
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader',
],
})
return config
}
And the styles looks like this:
<style lang="sass" scoped>
button
background-color: red
</style>
So I'm getting this error when trying to compile:
SassError: Invalid CSS after "": expected 1 selector or at-rule, was "button"
on line 1 of C:\Code\testproj\src\components\UI\TestComponent.vue
And if I change my style to this:
<style lang="sass" scoped>
button {
background-color: red
}
</style>
All works, but that's not a sass syntax.
I was having this exact same issue and I was able to solve it. The issue is from the webpack config. If you're using SASS, your webpack.config.js file in your .storybook folder should look like this:
module.exports = ({ config }) => {
config.module.rules.push({
test: /\.sass$/,
use: [
require.resolve("vue-style-loader"),
require.resolve("css-loader"),
{
loader: require.resolve("sass-loader"),
options: {
sassOptions: {
indentedSyntax: true
}
}
}
],
});
return config;
};
And if you're using SCSS, then it should be like this:
module.exports = ({ config }) => {
config.module.rules.push({
test: /\.scss$/,
use: [
require.resolve("vue-style-loader"),
require.resolve("css-loader"),
require.resolve("sass-loader"),
],
});
return config;
};
I was able to figure this out while reading the Vue Loader Docs
The problem is that in your webpack config, you are telling webpack that only use sass-loader when de extension of your file was test: /.s[ac]ss$/i That is to say .sass or .scss. However the extension of your file is .vue, because you are using sass in the vue file of your component.
With that configuration, try to put your sass style in a .sass file and check if works
For anyone using React 17+ with Storybook 6.4.9+, I had a similar problem where the Storybook/webpack build was not including my SCSS files. This configuration in .storybook/main.js worked for me:
module.exports = {
"stories": [
"../src/**/*.stories.mdx",
"../src/**/*.stories.#(js|jsx|ts|tsx)"
],
"addons": [
"#storybook/addon-links",
"#storybook/addon-essentials"
],
"framework": "#storybook/react",
webpackFinal: async (config) => {
// add SCSS support for CSS Modules
config.module.rules.push({
test: /\.scss$/,
use: [
require.resolve("style-loader"),
require.resolve("css-loader"),
require.resolve("sass-loader"),
],
});
return config;
}
}
I spend a lot of time to find better solution. It is may main.js config file for Storybook 6.4.9:
const path = require('path');
module.exports = {
"stories": [
"../src/**/*.stories.#(js|jsx|ts|tsx|mdx)"
],
"addons": [
"#storybook/addon-essentials",
"#storybook/addon-actions",
"#storybook/addon-controls",
"#storybook/addon-links",
{
name: '#storybook/preset-scss',
options: {
sassLoaderOptions: {
implementation: require('node-sass'), // ATTENTION: We need to use "node-sass" instead "sass/dart-sass"
sassOptions: {
indentedSyntax: true
},
},
}
},
"#storybook/addon-postcss",
],
"framework": "#storybook/vue",
features: {
babelModeV7: true,
},
webpackFinal: async (config, { configType }) => {
// `configType` has a value of 'DEVELOPMENT' or 'PRODUCTION'
// You can change the configuration based on that.
// 'PRODUCTION' is used when building the static version of storybook.
// ATTENTION: Need to preload "global.sass" style for all elements;
config.module.rules.map(rule => {
if (rule.test instanceof RegExp && rule.test.toString() === '/\\.s[ca]ss$/') {
rule.use.push({
loader: require.resolve('sass-resources-loader'),
options: {
resources: [
path.resolve(__dirname, '../src/styles/global.sass')
]
}
})
}
return rule
})
// ATTENTION: Need to compile "Pug" templates.
config.module.rules.push(
{
test: /\.pug$/,
oneOf: [
// this applies to `<template lang="pug">` in Vue components
{
resourceQuery: /^\?vue/,
use: ['pug-plain-loader']
},
// this applies to pug imports inside JavaScript
{
use: ['raw-loader', 'pug-plain-loader']
}
]
}
);
// Return the altered config
return config;
},
}

How to enable PurgeCSS for 3rd-part CSS

I am using #mdi/font in my SSR Nuxt project.
How can I enable purgeCSS for CSS from #mdi/font?
nuxt.config.js
module.exports = {
css: [
'#/assets/scss/app.scss'
],
...
}
assets/scss/app.scss
#import '~#mdi/font/css/materialdesignicons';
I try to config like below, but it just remove all the css
(example from purgecss.com)
nuxt.config.js
module.exports = {
...
build: {
postcss: {
plugins: {
'#fullhuman/postcss-purgecss': {
content: ['./pages/**/*.vue', './layouts/**/*.vue', './components/**/*.vue'],
whitelist: ['html', 'body']
}
}
}
}
}
I fixed it by using nuxt-purgecss
nuxt.config.js
module.exports = {
buildModules: [
'nuxt-purgecss'
]
}

Rollup not allowing SASS variables

I'm trying to setup a SASS structure in my Rollup config that would allow me to use variables throughout the application. I'd like to use postcss + autoprefixer. I've setup the following in my plugins array:
postcss({
modules: false,
extensions: ['.css', '.sass', '.scss'],
output: false,
extract: true,
plugins: [autoprefixer],
use: [
[
'sass', {
includePaths: [path.join(__dirname, 'scss')]
}
]
]
})
That works well, I'm able to import my SCSS files within my components ie. import "./App.scss";.
The problem I'm facing is I have a number of global variables declared in App.scss and I'd like to use those variables in components that are imported in children.
How would I go about doing that? I thought this plugin would resolve all the SCSS, concat then run postcss + SASS against it, but seems like that's not the case.
Adding my github comment here:
https://github.com/sveltejs/language-tools/issues/232#issuecomment-801549706
This worked for me:
svelte.config.js
module.exports = {
preprocess: autoPreprocess({
scss: { prependData: `#import 'src/styles/main.scss';`},
postcss: { plugins: [require('autoprefixer')] }
}),
#};
rollup.config.js
svelte({
dev: !production, // run-time checks
// Extract component CSS — better performance
css: css => css.write(`bundle.css`),
hot: isNollup,
preprocess: [
autoPreprocess({
scss: { prependData: `#import 'src/styles/main.scss';`},
postcss: { plugins: [postcssImport()] },
defaults: { style: 'postcss' }
})
]
}),
App.svelte
<style global lang="scss">
</style>
If you want the errors in terminal to go away on rollup.config.js
svelte({
dev: !production, // run-time checks
// Extract component CSS — better performance
css: css => css.write(`bundle.css`),
hot: isNollup,
preprocess: [
autoPreprocess({
scss: { prependData: `#import 'src/styles/main.scss';`},
postcss: { plugins: [postcssImport()] },
defaults: { style: 'postcss' }
})
],
onwarn: (warning, handler) => {
const { code, frame } = warning;
if (code === "css-unused-selector")
return;
handler(warning);
}
}),
The coolest thing is my main.scss file can import partials.
#import 'resets';
#import 'border_box';
#import 'colors';
#import 'fonts';
#import 'forms';
Documentation here: https://github.com/sveltejs/svelte-preprocess/blob/main/docs/getting-started.md

How to process css with postcss inside sapper-template with rollup

Having trouble using rollup-plugin-postcss with sapper-template:
npx degit sveltejs/sapper-template#rollup my-app
npm install rollup-plugin-postcss --save-dev
install various postcss plugin
create src/css/main.css
add import './css/main.css'; to the top line of src/client.js
*edit rollup.config.js
*add postcss.config.js
*going wrong here? I have tried several variations.
// rollup.config.js
...
import postcss from 'rollup-plugin-postcss'
...
export default {
client: {
input: config.client.input(),
output: config.client.output(),
plugins: [
replace({
'process.browser': true,
'process.env.NODE_ENV': JSON.stringify(mode)
}),
svelte({
dev,
hydratable: true,
emitCss: true
}),
resolve(),
commonjs(),
postcss({
// extract: true,
// sourceMap: true,
plugins: [require('autoprefixer')]
}),
...
// postcss.config.js
module.exports = {
plugins: {
...
autoprefixer: {}
}
};
No real error message, once I add postcss to the plugins in the client:{} of rollup.config.js - css breaks on the site.
This is a matter of simply putting the svelte plugin config together properly. I would recommend you use svelte-preprocess and setup your rollup.config.js as follows:
import autoPreprocess from 'svelte-preprocess';
const preprocessOptions = {
postcss: {
plugins: [
require('postcss-import'),
require('postcss-preset-env')({
stage: 0,
browsers: 'last 2 versions',
autoprefixer: { grid: true }
}),
...
]
}
};
...
export default {
client: {
plugins: [
svelte({
preprocess: autoPreprocess(preprocessOptions),
dev,
hydratable: true,
emitCss: true
}),
...
As you see here, you need to set the preprocess option of the svelte plugin.