How do I import scss files from #material using rollup? - sass

I have a simple rollup project that has the following structure
src
index.mjs
style.sass
package.json
rollup.config.mjs
In my rollup file I create the plugin like this...
const pcss = postcss({
preprocessor: (content, id) => new Promise((resolve, reject) => {
const result = sass.renderSync({
file: id,
includePaths: ["src", "node_modules"]
})
resolve({ code: result.css.toString() })
}),
plugins: [
autoprefixer
],
extensions: ['.sass', '.scss']
})
Then I have the simple import in my sass file like this...
#import "#material/button/mdc-button";
But when I run this I get...
Error: File to import not found or unreadable: #material/button/mdc-button.
at options.error (/Users/jackiegleason/Code/jrg-material/packages/components/node_modules/node-sass/lib/index.js:291:26)
If I change to
#import "~#material/button/mdc-button";
I get a little closer with...
Error: File to import not found or unreadable: #material/elevation/mixins.
How do I get it to recognize the files without an extension so the other imports work?

I got it to work like this...
const pcss = postcss({
modules: true,
extensions: ['.sass', '.scss'],
namedExports: true,
plugins: [
autoprefixer
],
use: [
[
'sass', {
includePaths: [path.resolve('node_modules')]
}
]
]
})

Related

rollup postcss plugin doesn't seem to work with scss and CSS Modules

The symptom
When are run rollup -c I get a reasonable build, but I get this error if I use the SCSS double slash comments:
CssSyntaxError: //../packages/core/src/styles/layout.module.scss:56:8: Unknown word
You tried to parse SCSS with the standard CSS parser; try again with the postcss-scss parser
As far as I can tell, I have setup the plugin to use sass and to use CSS Modules. When I try to set the parser to "postcss-scss" I get this other error:
[!] (plugin postcss) TypeError: node.getIterator is not a function
rollup.config.js
import url from "#rollup/plugin-url";
import svgr from "#svgr/rollup";
import autoprefixer from "autoprefixer";
import { resolve } from "path";
import postcssNormalize from "postcss-normalize";
import babel from "rollup-plugin-babel";
import peerDepsExternal from "rollup-plugin-peer-deps-external";
import postcss from "rollup-plugin-postcss";
import { nodeResolve } from "#rollup/plugin-node-resolve";
import commonjs from "#rollup/plugin-commonjs";
import typescript from "#rollup/plugin-typescript";
import packageJson from "./package.json";
export default [
{
input: "src/components/index.ts",
output: [
{
file: `${packageJson.main}`,
format: "cjs",
sourcemap: true,
},
{
file: `${packageJson.module}`,
format: "esm",
sourcemap: true,
},
],
plugins: [
// include peer deps in the package
peerDepsExternal(),
// The next 2 allow importing commonjs packages like classnames
commonjs(),
nodeResolve(),
// transform
babel({
exclude: "node_modules/**",
}),
typescript({
typescript: require("typescript"),
tsconfig: "./tsconfig-prod.json",
}),
postcss({
plugins: [autoprefixer(), postcssNormalize()],
// exclude: "src/styles/**/*.scss",
namedExports: true,
sourceMap: true,
extract: false,
// modules: true,
autoModules: true,
minimize: true,
extensions: [".scss"],
use: ["sass"],
// parser: "postcss-scss",
}),
url(),
svgr(),
],
},
};
There are a couple of commented out options, which I have also tried. Yes, I can switch comment type - the sheer number of files notwithstanding, but it bothers me that this setup is not quite working, so any help would be much appreciated.
In the src/components folders I have this folder strcuture pattern for each component:
components ->
> Button ->
> index.ts
> Button.tsx
> Button.module.scss

Rollup CommonJS plugin throwing error when importing Sass files in dependencies

I'm using Rollup on a Sapper project found here: https://github.com/darryl-snow/perfect-cookie
Yesterday I ran npm update and since then when I run npm run dev I get the following error:
✗ client
Invalid CSS after "...-features: list": expected expression (e.g. 1px, bold), was ".append($available-"
✗ server
Invalid CSS after "...-features: list": expected expression (e.g. 1px, bold), was ".append($available-"
internal/modules/cjs/loader.js:985
throw err;
^
My rollup config:
import resolve from '#rollup/plugin-node-resolve'
import replace from '#rollup/plugin-replace'
import commonjs from '#rollup/plugin-commonjs'
import svelte from 'rollup-plugin-svelte'
import postcss from 'rollup-plugin-postcss'
import babel from 'rollup-plugin-babel'
import { terser } from 'rollup-plugin-terser'
import config from 'sapper/config/rollup.js'
import pkg from './package.json'
const mode = process.env.NODE_ENV
const dev = mode === 'development'
const legacy = !!process.env.SAPPER_LEGACY_BUILD
const onwarn = (warning, onwarn) =>
(warning.code === 'CIRCULAR_DEPENDENCY' && /[/\\]#sapper[/\\]/.test(warning.message)) || onwarn(warning)
const postcssOptions = () => ({
extensions: ['.scss', '.sass'],
extract: false,
minimize: true,
use: [
[
'sass',
{
includePaths: ['./src/theme', './node_modules'],
},
],
],
})
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({
browser: true,
dedupe: ['svelte'],
}),
commonjs(),
postcss(postcssOptions()),
legacy &&
babel({
extensions: ['.js', '.mjs', '.html', '.svelte'],
runtimeHelpers: true,
exclude: ['node_modules/#babel/**'],
presets: [
[
'#babel/preset-env',
{
targets: '> 0.25%, not dead',
},
],
],
plugins: [
'#babel/plugin-syntax-dynamic-import',
[
'#babel/plugin-transform-runtime',
{
useESModules: true,
},
],
],
}),
!dev &&
terser({
module: true,
}),
],
onwarn,
},
server: {
input: config.server.input(),
output: config.server.output(),
plugins: [
replace({
'process.browser': false,
'process.env.NODE_ENV': JSON.stringify(mode),
}),
svelte({
generate: 'ssr',
dev,
}),
resolve({
dedupe: ['svelte'],
}),
commonjs(),
postcss(postcssOptions()),
],
external: Object.keys(pkg.dependencies).concat(
require('module').builtinModules || Object.keys(process.binding('natives'))
),
onwarn,
},
serviceworker: {
input: config.serviceworker.input(),
output: config.serviceworker.output(),
plugins: [
resolve(),
replace({
'process.browser': true,
'process.env.NODE_ENV': JSON.stringify(mode),
}),
commonjs(),
!dev && terser(),
],
onwarn,
},
}
I've tried rm -rf ./node_modules && npm install but still getting the same error. It looks like commonJS is loading dependencies and finding one where it's expecting CSS but getting Sass... I'm completely new to rollup, any ideas?
You should probably consider installing the latest major version of #rollup/plugin-commonjs. The one you're currently using has a bug with Sapper (which I've encountered while running your repo instead of the one in the question) and it was fixed in the later versions.
After upgrading that, your project seems to start up fine.
While you're at it, upgrade the other major version upgrades, very likely that most of them will go by without errors.

Export my CSS vars with my module using rollup?

I have a little module that I am sharing across a few projects. It is successfully exporting components, but now I'd like to get my global style vars, like $contoso-primary: #ff0000 to be exported as well so we can start sharing CSS vars in my consuming app, like background-color: $contoso-primary. I'm using the rollup.js, is this possible with this library or with its plugins? If so, what plugin am I looking for? I've tried postcss already but doesn't appear to work unless I'm missing something.
export default {
input: 'src/index.js',
output: [
{
file: pkg.main,
format: 'cjs',
sourcemap: true
},
{
file: pkg.module,
format: 'es',
sourcemap: true
}
],
plugins: [
external(),
postcss({
extract: true
}),
url(),
svgr(),
babel({
exclude: 'node_modules/**'
}),
resolve(),
commonjs()
],
onwarn(warning, warn) {
if (
warning.code === 'CIRCULAR_DEPENDENCY'
&& warning.importer.indexOf('node_modules/semantic-ui-react') > -1
) return;
warn(warning);
}
};
my scss file that has my vars looks something like:
$primary: #177757,
$secondary: #D50000
and in the consuming project I'd like to refer to these in my scss files like:
.button {
background: $primary
}
I can't get an .css file into my dist folder, and the documenation on rollup-plugin-postcss is a little light.
postcss-simple-var this plugin will able to share sass like variables.
plugins: [
postcss({
plugins: [
simplevars()
],
extensions: [ '.css' ],
}),
...
]
for more information read this article.
I was able to make this work by duplicating the variable declarations in both the postcss.config.js and rollup.config.js
Rollup config:
import postcss from "rollup-plugin-postcss";
import postcssSimpleVars from "postcss-simple-vars";
const variables = require("./pathTo/variableConfig.js");
...
const config = {
...
plugins: [
postcss({
postcssSimpleVars({
variables: function () {
return variables;
}
}),
})
]
postCSS config:
const variables = require("./variableConfig.js");
plugins: [
...
require("postcss-simple-vars")({
variables: variables
})
]
variableConfig.js:
const baseDir = "../src/utils/constants";
const { COLORS } = require(`${baseDir}/colors`);
const { MQ } = require(`${baseDir}/mediaQueries`);
const { BREAKPOINTS } = require(`${baseDir}/breakpoints`);
const cssVars = Object.assign(COLORS, MQ, BREAKPOINTS);
module.exports = cssVars;

Laravel mix webpack - Ignore locales when importing Moment.js

I would like to load 2 locales en-gb and fr-ch only from Moment.js , then assign the moment class to the scopewindow to use the library everywhere in my Vuejs components.
Currently, my app.js has this require line:
window.moment = require('moment')
I am suspecting it can be accomplished thanks to the solutions here (adding IgnorePlugin and ContextReplacementPlugin to webpack.config.js):
plugins.push(new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en-gb|fr-ch/))
module.exports.plugins = plugins;
OR
plugins.push(new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/))
module.exports.plugins = plugins;
Where should you add these pieces of code (webpack.config.js and/or app.js and/or webpack.mix.js) to ignore all other locales when importing momentjs?
mix.webpackConfig({
plugins: [
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
]
})
Source: https://laracasts.com/discuss/channels/elixir/laravel-mix-prevent-momentjs-locales
mix.webpackConfig( webpack => {
plugins: [
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
]
});
this way you dont have to import webpack on the top of your file, which sometimes can cause errors.
and you also can put other necessary options like this
mix.webpackConfig( webpack => {
plugins: [
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
],
resolve: {
extensions: ['.js', '.vue'],
alias: {
'#': __dirname + '/resources',
'#root': __dirname,
'#pages': __dirname + '/resources/js/pages'
},
fallback: { "path": false },
},
});

How to import Foundation's SCSS with Webpack 2?

I'm trying to use Foundation with Webpack 2 using the sass-loader.
I'm importing Foundation with
#import 'foundation-sites/scss/foundation';
And get an import error as it can't find foundation. Reading the docs for sass-loader suggests that I should actually use:
#import '~foundation-sites/scss/foundation';
Which fixes the import error but creates a new problem.
The error I receive is
ModuleBuildError in
Module build failed:
#import "normalize";
^
File to import not found or unreadable: normalize
File to import not found or unreadable: normalize
Parent style sheet: ... /node_modules/foundation-sites/scss/foundation.scss
in ... /node_modules/foundation-sites/scss/foundation.scss (line 9, column 1)
In my webpack config file I'm also using the ExtractTextPlugin as below:
module: {
rules: [
{
test: /\.(scss|css)$/,
loader: ExtractTextPlugin.extract({
fallbackLoader: 'style-loader',
loader: [
{
loader: 'css-loader'
},
{
loader: 'sass-loader',
query: {
includePaths: [path.resolve(__dirname, "./node_modules")]
}
}
]
})
}
]
},
resolve: {
modules: ['node_modules']
}
I believe this comes from the webpack isn't resolving to the node_modules folder for some reason but unsure where the cause comes from.
Try this, as that the only thing that worked for me.
new webpack.LoaderOptionsPlugin({
options: {
context: '/', // <- putting this line right under "options" did the trick
sassLoader: {
includePaths: [
path.resolve(__dirname, 'vendor/zurb/foundation/scss'),
]
}
}
})

Resources