CssSyntaxError in plugin "gulp-postcss" / You tried to parse SCSS with the standard CSS parser; try again with the postcss-scss parser - sass

I'm using this plugin for years now, and it's the first time I get this error.
I'm working on an old project which i recently upgraded to the latests versions of node & npm, so I'm working with node v16.15.0 and npm v8.5.5. I also upgraded all of my npm packages to their latests versions (yes, I like to live dangerously).
Gulp v4.0.2 with gulpfile.js as such (there is some commented code in it because I'm still in the process of making it work with these versions of node & npm. Originally, this project was running fine with node v12.6.0 and npm v7.20.03 .
After upgrading, I encountered many errors, as for example the need to switch from node-sass to dart-sass, because it's deprecated. ) :
// MODULES
// ----------------------------------------------------------------------------
const gulp = require('gulp'),
//sass = require('gulp-sass')(require('dart-sass'), require('node-sass')),
sass = require('gulp-sass')(require('sass'), require('dart-sass')),
globImporter = require('node-sass-glob-importer'),
postcss = require('gulp-postcss'),
stylelint = require('gulp-stylelint'),
svgstore = require('gulp-svgstore'),
rename = require('gulp-rename'),
cssnano = require('cssnano'),
uglifyjs = require('uglify-js'),
del = require('del'),
autoprefixer = require('autoprefixer'),
// This is based on node-sass, which is deprecated
// find a replacement which works with something else...
//inliner = require('sass-inline-svg'),
connect = require('gulp-connect'),
openBrowser = require('open');
// Basic config for paths (cfg = config)
// ----------------------------------------------------------------------------
const cfg = {
scssDir: 'src/scss/',
builtCssDir: 'dist/css/',
scssPattern: '**/*.scss',
svgDir: 'src/assets/svg/',
compiledSvgDir: 'dist/svg/',
compiledSvgFileName: 'symbols.twig',
svgPattern: '**/*.svg',
jsLibsDir: 'src/js/libs/',
jsDir: 'src/js/',
compiledJsLibsDir: 'dist/js/libs/',
compiledJsDir: 'dist/js/',
jsPattern: '*.js'
}
// Launch a server
// ----------------------------------------------------------------------------
function serve() {
connect.server({
port: 8080,
livereload: true,
root: ['src']
});
}
// Open application in browser
// ----------------------------------------------------------------------------
async function open() {
await openBrowser('http://localhost:8080/');
}
// Construct style.css (Combine all scss files into one css final file)
// ----------------------------------------------------------------------------
function style() {
return gulp
.src(cfg.scssDir+cfg.scssPattern)
// Test files with `gulp-stylelint` to ckeck the coding style
/*.pipe(stylelint({
reporters: [
{formatter: 'compact', console: true}
]
}))*/
/*.pipe(sass({
importer: globImporter(),
functions: {
svg: inliner(cfg.svgDir, {encodingFormat: 'uri'})
}
}))*/
.on('error', sass.logError)
// Use postcss with autoprefixer and compress the compiled file using cssnano
.pipe(postcss([autoprefixer(), cssnano()]))
.pipe(gulp.dest(cfg.builtCssDir))
}
// Construct svg symbol file (Combine svg files into one with <symbol> elements)
// ----------------------------------------------------------------------------
/*function svg() {
return gulp
.src(cfg.svgDir+cfg.svgPattern, {base: cfg.svgDir})
.pipe(rename((filePath) => {
const name = filePath.dirname !== '.' ? filePath.dirname.split(filePath.sep) : []
name.push(filePath.basename)
filePath.basename = `symbol-${name.join('-')}`
}))
.pipe(svgstore({ inlineSvg: true }))
.pipe(rename(cfg.compiledSvgFileName))
.pipe(gulp.dest(cfg.compiledSvgDir));
}*/
// Catch JS libs and transfer it to dist folder
// ----------------------------------------------------------------------------
async function jslibs() {
return gulp
.src(cfg.jsLibsDir+cfg.jsPattern)
.pipe(gulp.dest(cfg.compiledJsLibsDir));
}
// Compile JS
// ----------------------------------------------------------------------------
async function js() {
return gulp
.src(cfg.jsDir+cfg.jsPattern)
.pipe(gulp.dest(cfg.compiledJsDir));
}
// Watcher
// ----------------------------------------------------------------------------
function watch() {
gulp.watch('../'+cfg.scssDir+cfg.scssPattern, style)
gulp.watch('../'+cfg.scssDir+cfg.scssPattern)
gulp.watch(cfg.scssDir+cfg.scssPattern, style)
gulp.watch(cfg.svgDir+cfg.svgPattern, svg)
gulp.watch(cfg.scssDir+cfg.scssPattern);
}
// Empty the build folder of its front asset like css & svg (We're not emptying it totally, because there is other assets in it)
function clean() {
return del([
cfg.builtCssDir,
cfg.compiledSvgDir+'/'+cfg.compiledSvgFileName,
cfg.compiledJsDir
], {force: true});
}
clean.description = 'Delete the content of the build folder.';
// Serve
// ----------------------------------------------------------------------------
// Launch server
const launch = gulp.series(open, serve);
// Builder
// ----------------------------------------------------------------------------
// Regenerate the build folder.
const build = gulp.series(clean, style, jslibs, js);
// Export default task
// ----------------------------------------------------------------------------
// Regenerate the build folder & launch watcher
const defaultTask = gulp.series(clean, style, jslibs, js, watch);
// Export Tasks
// ----------------------------------------------------------------------------
module.exports = {
open,
serve,
launch,
clean,
style,
jslibs,
js,
build,
watch,
default: defaultTask
};
I get the following error when I try to throw my gulp default task in my terminal :
error
[11:42:55] CssSyntaxError in plugin "gulp-postcss"
Message:
/Users/emma/Desktop/www/photosbroth/src/scss/styles.scss:3:1: Unknown word
You tried to parse SCSS with the standard CSS parser; try again with the postcss-scss parser
1 | #charset "UTF-8";
2 |
> 3 | // Import EXTERNAL libs
| ^
4 | // - `sass-mq` for breakpoints management
5 | #import '../../node_modules/sass-mq/mq';
Apparently, it doesn't like the // scss comments, which were perfectly fine before I tried to upgrade my stack.
Could anyone help please ? I wasn't able to find a solution to this.
I tried this in the gulpfile :
postcss = require('gulp-postcss')(require('postcss'))
this
postcss = require('gulp-postcss')(require('postcss-scss'))
and this
postcss = require('gulp-postcss')(require('postcss'), require('postcss-scss'))
None of those expressions worked.
Is this a bug or anything else ? Am I missing something ?
Thank you.

Related

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

Gulp 3.9 to 4 Migration

I know this has been asked many times before, but none of the answers helped me to solve my problem migrating gulp 3 to 4. We didn't necessarily have to upgrade to version 4 of gulp, but updating Node.js from 10 to 12 forced us to do so, since Node.js 12 doesn't support gulp 3 anymore. Here are just 2 of files in our build process, I think that it should be enough to understand what the problem is from these files alone, but I can add the other files if need be. And I have also removed the contents of most functions for brevity.
// gulpfile.js
'use strict';
var gulp = require('gulp');
var wrench = require('wrench');
/**
* This will load all js or coffee files in the gulp directory
* in order to load all gulp tasks
*/
wrench.readdirSyncRecursive('./gulp').filter(function (file) {
return (/\.(js|coffee)$/i).test(file);
}).map(function (file) {
require('./gulp/' + file);
});
/**
* Default task clean temporaries directories and launch the
* main optimization build task
*/
//gulp.task('default', ['clean'], function () { <-- Original line, worked in gulp 3.9
function main(done)
{
gulp.start(build);
done();
}
exports.default = gulp.series(clean, main);
And another file:
// build-dev.js
'use strict';
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var $ = require('gulp-load-plugins')({
pattern: ['gulp-*', 'main-bower-files', 'uglify-save-license', 'del']
});
//gulp.task('html-dev', ['inject'], function () <-- Original line, worked in gulp 3.9
function htmlDev()
{
// Removed for brevity...
}
exports.htmlDev = gulp.series(exports.inject, htmlDev); <-- this is the line that fails
//gulp.task('fonts-dev', function () <-- Original line, worked in gulp 3.9
function fontsDev()
{
// Removed for brevity...
}
exports.fontsDev = fontsDev;
//gulp.task('other-dev', function () <-- Original line, worked in gulp 3.9
function otherDev()
{
// Removed for brevity...
}
exports.otherDev = otherDev;
//gulp.task('clean', function () <-- Original line, worked in gulp 3.9
function clean()
{
// Removed for brevity...
}
exports.clean = clean;
//gulp.task('build:dev', ['html-dev', 'fonts-dev', 'other-dev']); <-- Original line, worked in gulp 3.9
exports.buildDev = gulp.series(exports.htmlDev, fontsDev, otherDev);
And when I run gulp I get the following error:
AssertionError [ERR_ASSERTION]: Task never defined: undefined
at getFunction (F:\Dev\DigitalRural\Main\Mchp.DigitalRural.Portal\node_modules\undertaker\lib\helpers\normalizeArgs.js:15:5)
at map (F:\Dev\DigitalRural\Main\Mchp.DigitalRural.Portal\node_modules\arr-map\index.js:20:14)
at normalizeArgs (F:\Dev\DigitalRural\Main\Mchp.DigitalRural.Portal\node_modules\undertaker\lib\helpers\normalizeArgs.js:22:10)
at Gulp.series (F:\Dev\DigitalRural\Main\Mchp.DigitalRural.Portal\node_modules\undertaker\lib\series.js:13:14)
at Object.<anonymous> (F:\Dev\DigitalRural\Main\Mchp.DigitalRural.Portal\gulp\build-dev.js:61:24)
at Module._compile (internal/modules/cjs/loader.js:936:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:947:10)
at Module.load (internal/modules/cjs/loader.js:790:32)
at Function.Module._load (internal/modules/cjs/loader.js:703:12)
at Module.require (internal/modules/cjs/loader.js:830:19) {
generatedMessage: false,
code: 'ERR_ASSERTION',
actual: undefined,
expected: true,
operator: '=='
}
The error is in the second file, build-dev.js, and I indicate it in the code I provided. I have been trying to follow tutorials and SO questions, but to no avail. What gives?
OK, I apparently got it all wrong (yup, makes sense, from a guy that doesn't know either gulp 3 nor gulp 4 :)).
Since gulp 4 has some quite substantial changes, I had to actually rewrite the whole process (not the tasks themselves, they are more or less fine, except some here and there).
So basically, I changed the tasks to functions, used exports for some tasks to make them well known, and used series/parallel for the tasks' flow.
But I have another problem, related to the destination path, but that's a topic for another post.
Thanks everyone.

BlueprintJS Module build failed due to syntax error

I am getting the following errors when I run npm run storybook.
I am almost positive it's due to something I am missing in my webpack.config or a missing npm package.
I have researched as much as I know how/what to look for to fix this issue and would appreciate a helping hand.
Link to my sample Github repo
https://github.com/hungrysquirrel/storybookv3/commit/85ba4e87ad7b27fbb3433a61c49da0fc254f528d
Errors I can see in my terminal when I start my server
ERROR in ./~/css-loader?{"importLoaders":1}!./~/postcss-loader/lib?{"ident":"postcss","plugins":[null,null]}!./~/#blueprintjs/core/dist/index.js
Module build failed: Syntax Error
(7:1) Unknown word
5 | * and https://github.com/palantir/blueprint/blob/master/PATENTS
6 | */
> 7 | "use strict";
| ^
8 | function __export(m) {
9 | for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
# ./~/css-loader?{"importLoaders":1}!./~/postcss-loader/lib?{"ident":"postcss"}!./css/global.css 3:10-151
# ./css/global.css
# ./stories/index.js
# ./.storybook/config.js
# multi ./~/#storybook/react/dist/server/config/polyfills.js ./~/#storybook/react/dist/server/config/globals.js (webpack)-hot-middleware/client.js?reload=true ./.storybook/config.js
ERROR in ./~/css-loader?{"importLoaders":1}!./~/postcss-loader/lib?{"ident":"postcss","plugins":[null,null]}!./~/#blueprintjs/table/src/table.scss
Module build failed: Syntax Error
(1:1) Unknown word
> 1 | // Copyright 2016 Palantir Technologies, Inc. All rights reserved.
| ^
2 | // Licensed under the BSD-3 License as modified (the “License”); you may obtain a copy
3 | // of the license at https://github.com/palantir/blueprint/blob/master/LICENSE
# ./~/css-loader?{"importLoaders":1}!./~/postcss-loader/lib?{"ident":"postcss"}!./css/global.css 4:10-167
I just had the same exact issue. I managed to get it to work by
in global.css:
// replacing
#import '~#blueprintjs/core';
// by the more explicit
#import "~#blueprintjs/core/dist/blueprint.css";
in webpack.config.js I included loaders for css and files:
{ test: /\.css$/, use: ["style-loader", "css-loader"] },
{
test: /\.(eot|ttf|woff|woff2)$/,
// We need to resolve to an absolute path so that this loader
// can be applied to CSS in other projects (i.e. packages/core)
loader: require.resolve("file-loader") + "?name=fonts/[name].[ext]"
},
Solved
Includes for scss files within .css file - BAD
Webpack config was incorrect. The setup below fixes the issue
const path = require('path');
const srcPath = path.join(__dirname, '../src');
const genDefaultConfig = require('#storybook/react/dist/server/config/defaults/webpack.config.js');
module.exports = (baseConfig, env) => {
const config = genDefaultConfig(baseConfig, env);
config.module.rules.push({
test: /\.scss$/,
use: [{
loader: "style-loader" // creates style nodes from JS strings
}, {
loader: "css-loader" // translates CSS into CommonJS
}, {
loader: "sass-loader" // compiles Sass to CSS
}]
})
config.resolve.extensions.push('.css', '.scss', '.sass');
return config;
};

Gulp not copying Angular2 to lib-npm

I'm following this tutorial. http://www.c-sharpcorner.com/article/using-mvc-6-and-angularjs-2-with-net-core/
I have gotten to the point of using gulp to copy files to the lib-npm folder. All the expected files copy except angular. I receive no error message, the files just are there.
here is my gulp file
/// <binding />
/*
This file in the main entry point for defining Gulp tasks and using Gulp plugins.
Click here to learn more. http://go.microsoft.com/fwlink/?LinkId=518007
*/
"use strict";
var gulp = require("gulp");
var root_path = {
webroot: "./wwwroot/"
};
//library source
root_path.nmSrc = "./node_modules/";
//library destination
root_path.package_lib = root_path.webroot + "lib-npm/";
gulp.task("copy-systemjs", function () {
return gulp.src(root_path.nmSrc + '/systemjs/dist/**/*.*', {
base: root_path.nmSrc + '/systemjs/dist/'
}).pipe(gulp.dest(root_path.package_lib + '/systemjs/'));
});
gulp.task("copy-angular2", function () {
return gulp.src(root_path.nmSrc + '/angular2/bundles/**/*.js', {
base: root_path.nmSrc + '/angular2/bundles/'
}).pipe(gulp.dest(root_path.package_lib + '/angular2/'));
});
gulp.task("copy-es6-shim", function () {
return gulp.src(root_path.nmSrc + '/es6-shim/es6-sh*', {
base: root_path.nmSrc + '/es6-shim/'
}).pipe(gulp.dest(root_path.package_lib + '/es6-shim/'));
});
gulp.task("copy-rxjs", function () {
return gulp.src(root_path.nmSrc + '/rxjs/bundles/*.*', {
base: root_path.nmSrc + '/rxjs/bundles/'
}).pipe(gulp.dest(root_path.package_lib + '/rxjs/'));
});
gulp.task("copy-all", ["copy-rxjs", 'copy-angular2', 'copy-systemjs', 'copy-es6-shim']);
I have also noticed that my .\node_modules\Angular2 folder in my project doesn't have an .js files in it. Is this normal?
Angular2 version is 1.0.2
I receive the following errors on build because the files are missing
Cannot find name 'Component'.
Build:Cannot find module 'angular2/core'.
Build:Cannot find module 'angular2/platform/browser'.
Build:Cannot find name 'Component'.
Cannot find module 'angular2/core'.
Cannot find module 'angular2/platform/browser'
I would suggest you not to copy node_modules every time you build an app. You can easily amend the UseStaticFiles middleware inside the Startup.cs class as described here. By doing this your node_modules stay where they are and you don't need to repeatedly copy them.
Btw. Recently (before switching to UseStatisFiles modification) I have done the same in the Gulp and the following has worked well:
gulp.task('build-angular-js', function () {
return gulp.src(paths.angularJs)
.pipe(cache('linting'))
.pipe(gulp.dest(paths.jsNgDest));
});
..where paths equals to:
var paths = {
webroot: "./wwwroot/",
angularJs: [
"./node_modules/core-js/client/shim.min.js",
"./node_modules/zone.js/dist/zone.js",
"./node_modules/reflect-metadata/Reflect.js",
"./node_modules/systemjs/dist/system.src.js",
"./App/External/systemjs.config.js",
"./node_modules/#angular/**/*.js",
"./node_modules/rxjs/**/*.js"
],
appJs: [
"./App/App/**/*.js"
]
};
paths.jsDest = paths.webroot + "app";
paths.jsNgDest = paths.webroot + "app";
The complete template and all sources including gulpfile.js can be found here on GitHub. Note that cache is a gulp plugin to avoid copying not modified files. As said above though - better to avoid copying node_modules.

Running grunt on windows 8

I am trying to run grunt on an existing project on a windows 8 machine.
I've installed grunt-cli globally,by running:
npm install -g grunt-cli
However when trying to run the project with:
grunt develop
I get this error:
Warning: Unable to write "preview.html" file <Error code: EPERM>. Use --force to continue.
Aborted due to warnings.
Then when running
grunt develop --force
I get this error:
Running "less:css/main.css" <less> task
Fatal error: Unable to write "css/main.css" file <Error code: EPERM>.
Any help you could provide on this would be most helpful,
thanks.
Update 1:
This is my Gruntfile.js
module.exports = function(grunt){
grunt.initConfig({
watch: {
less: {
files: ['**/*.less', '!less/_compiled-main.less'],
tasks: 'less'
},
html: {
files: ['preview-template.html', 'js/**/*.js', 'less/**/*.less', '!less/_compiled-main.less'],
tasks: ['includeSource', 'add-dont-edit-prefix-to-preview-html']
},
wysiwyg: {
files: ['less/wysiwyg.less'],
tasks: 'generate-wysiwyg-styles-js'
}
},
less: {
'css/main.css': 'less/_compiled-main.less',
'css/wysiwyg.css': 'less/wysiwyg.less',
options: {
dumpLineNumbers: 'comments'
}
},
includeSource: {
options: {
templates: {
},
},
dev: {
files: {
'preview.html': 'preview-template.html',
'less/_compiled-main.less': 'less/main.less'
}
}
},
connect: {
server: {
options: {
base: '.',
port: 8000
}
}
}
});
// Css preprocessor
grunt.loadNpmTasks('grunt-contrib-less');
// Watch for file changes and run other grunt tasks on change
grunt.loadNpmTasks('grunt-contrib-watch');
// Includes all js files in preview-template.html and saves as preview.html.
// Includes all less files in main.less and saves as _compiled-main.less
grunt.loadNpmTasks('grunt-include-source');
// Static http server
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.registerTask('generate-wysiwyg-styles-js', function(){
var css = grunt.file.read('css/wysiwyg.css');
css = css.replace(/\n/g, '')
var js = '// This file is generated automatically based on wysiwyg.less - don\' edit it directly!\n';
js += '// It needs to exist in JS form so we can include the CSS in the downloaded saved notes file';
js += "\napp.value('wysiwygStyles', '" + css + "');";
grunt.file.write('js/app/wysiwyg-styles.js', js)
})
grunt.registerTask('add-dont-edit-prefix-to-preview-html', function(){
var file = grunt.file.read('preview.html');
var prefix = '<!-- \n\n\n\n Don\'t edit this file, edit preview-template.html instead.' + new Array(20).join('\n') + ' -->';
file = file.replace('<!doctype html>', '<!doctype html>' + prefix)
grunt.file.write('preview.html', file);
});
grunt.registerTask('build-develop', [
'includeSource',
'less',
'generate-wysiwyg-styles-js',
'add-dont-edit-prefix-to-preview-html'
])
grunt.registerTask('develop', [
'build-develop',
'connect:server',
'watch'
]);
}
Try something like this maybe?
less: {
files: {
'css/main.css': 'less/_compiled-main.less',
'css/wysiwyg.css': 'less/wysiwyg.less'
},
options: {
dumpLineNumbers: 'comments'
}
}
Notice the files addition to the less array after grunt.initConfig
Let me know if it works.

Resources