ESBuild and postcss are adding \ (slashes) into my css and I can't figure out why - postcss

I have been coding along and have started to get these warning on compile now.
It seems that I have started to use "[:has" and the precompiler can't handle that. If this output is ok, I am ok with it, but if there is something that can be done to fix this, it would be great.
My console log...
▲ [WARNING] Expected "]" to go with "[" [css-syntax-error]
postcss:/home/encompass/Projects/SNAP/LOCAL/pp_alue/app/public/wp-content/themes/ppshp-modular-theme/src/assets/styles/style.pcss:9561:36:
9561 │ .language-switcher-container[\:has\(.language-switcher-selected\[aria-expanded\%3D\%22true\%2...
│ ^
╵ ]
The unbalanced "[" is here:
postcss:/home/encompass/Projects/SNAP/LOCAL/pp_alue/app/public/wp-content/themes/ppshp-modular-theme/src/assets/styles/style.pcss:9561:28:
9561 │ .language-switcher-container[\:has\(.language-switcher-selected\[aria-expanded\%3D\%22true\%2...
╵ ^
▲ [WARNING] Unexpected "]" [css-syntax-error]
postcss:/home/encompass/Projects/SNAP/LOCAL/pp_alue/app/public/wp-content/themes/ppshp-modular-theme/src/assets/styles/style.pcss:9561:98:
9561 │ ...e-switcher-container[\:has\(.language-switcher-selected\[aria-expanded\%3D\%22true\%22\]\)] {
╵
Looking into my css it does seem to be adding these "" (slashes) to the code. It is Halloween season and all, but I don't need any more slashes then I put in the code.'
Example of the problem output...
.language-switcher-container[\:has\(.language-switcher-selected\[aria-expanded\%3D\%22true\%22\]\)] {
background-color: var(--colors-primary-blue-10);
border-radius: 4px 4px 0 0;
}
.language-switcher-container:has(.language-switcher-selected[aria-expanded="true"]) {
background-color: var(--colors-primary-blue-10);
border-radius: 4px 4px 0 0;
}
My build configuration...
I seems that if I change the stage to 3 the errors stop, so it certainly seems to have something to do with postCssPresetEnv
const stylesPlugin = [
postCssPlugin({
plugins: [
postCssPresetEnv({ stage: 1}),
postCssEasyImport({ extensions: ['.css', '.pcss'] }),
postCssExtendRule,
postCssReporter(),
url({ url: 'inline' })
],
}),
];
const lint = async () => {
try {
const eslint = new ESLint();
const results = await eslint.lintFiles(['src/**/*.js']);
const formatter = await eslint.loadFormatter('stylish');
const resultText = formatter.format(results);
console.log(resultText);
} catch (err) {
console.error(err);
}
};
const buildScripts = async () => {
console.log('Building scripts ...');
try {
const timerStart = Date.now();
// Build code
await esbuild.build({
entryPoints: [
'src/endpoints/scripts.js',
'src/endpoints/scripts.admin.js',
],
format: 'iife',
bundle: true,
minify: true,
outdir: 'dist/',
plugins: [...stylesPlugin],
sourcemap: true,
external: ['*.svg', '*.woff', '*.css', '*.jpg', '*.png'],
});
const timerEnd = Date.now();
console.log(`Done! Scripts built in ${timerEnd - timerStart} ms.`);
} catch (error) {
console.log(error);
}
};
Other notes:
I checked for character encoding issues, and they don't seem to be anything but UTF-8
I am using the latest node.
node v18.12.0 (npm v8.19.2)

I eventually figure out how to at least make the error go away.
I stopped using :has() selectors as they are not compatible with firefox at the time of this post. I think eslint was bailing because of this and causes further errors down the pipeline.

Related

How to add typescript paths to storybook

I have a react application with a custom Webpack configuration.
After adding Webpack aliases that matches tsconfig.json file compilerOptions->paths field the aliases were recognized by webpack.
Since storybook comes with a built in Webpack configuration, my aliases are not read by Storybook and I'm getting the following error:
Module not found: Error: Can't resolve <path with typescript alias> in <some folder path>
In Storybook main.js file, add the following:
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
module.exports = {
...,
webpackFinal: async (config, { configType }) => {
config.resolve.plugins = [new TsconfigPathsPlugin()];<-- this line
return config;
}
};
You can install tsconfig-paths-webpack-plugin using the following command from the folder in which your application's package.json file resides:
npm i tsconfig-paths-webpack-plugin -D
Solution was derived from this discussion:
https://github.com/storybookjs/storybook/issues/6316
For future vistors of this question, since 15th July of 2022 storybooks can use Vite instead Webpack.
In that case I recommend using vite-tsconfig-paths instead of tsconfig-paths-webpack-plugin. If you are using TS paths in Vite, you probably already have this package installed.
Add this to your .storybook/main.js
const { mergeConfig } = require("vite")
const { default: tsconfigPaths } = require('vite-tsconfig-paths')
module.exports = {
// your previous configs and more...
viteFinal(config, { configType }) {
return mergeConfig(config, {
plugins: [
tsconfigPaths()
]
})
}
}
An alternative to accepted solution:
If you prefer not to install an external library such as tsconfig-paths-webpack-plugin, you can create a custom file, say:
tsconfig-webpack-utils.js
and do something similar to the following:
const { compilerOptions } = require('../tsconfig.json');
function getAliases() {
const baseUrl = getTSBaseUrl();
return Object.fromEntries(Object.entries(compilerOptions.paths).map(([key, value]) => {
return [
key.replace(/\/\*\*?$/,''),
value.map(entryPath => path.resolve(__dirname, baseUrl, entryPath.replace(/\/\*\*?$/,'/')))
]
}));
}
function getTSBaseUrl() {
return path.resolve(__dirname, `../${compilerOptions.baseUrl}`);
}
exports.addTsDefinitionsToWebpack = function(webpackConfig) {
if (!webpackConfig.resolve.modules) {
webpackConfig.resolve.modules = ['node_modules'];
}
webpackConfig.resolve.modules.push(getTSBaseUrl());
webpackConfig.resolve.alias = {
...webpackConfig.resolve.alias,
...getAliases()
};
}
This solution only works for very simple aliases. It is recommended to use an appropriate library or to expand this solution according to your needs.
You can then use it as follows in every webpack config you require it:
addTsDefinitionsToWebpack(webpackConfig);

Webpack#5 output.libraryTarget='system' breaks app

I have an old application and i have micro-frontend structure there. The application was using react-scripts#4 and this version had several vulnerabilities so i decided to upgrade it. While react-scripts#5 is not compatible with webpack#4, i needed to upgrade it too. However, I cannot use output.libraryTarget='system' or output.library.type='system' anymore. If i remove this part then app works but i cannot access micro-frontends. Here is my craco.config file;
import {
BabelOptions,
DevServerOptions,
EsLintOptions,
WebpackOptions,
} from '#craco/craco';
export default {
babel: {
plugins: [['#babel/plugin-proposal-decorators', { legacy: true }]],
} as BabelOptions,
eslint: {
enable: false,
} as EsLintOptions,
webpack: {
configure: (webpackConfig) => {
// use system
webpackConfig.output.libraryTarget = 'system';
delete webpackConfig.optimization;
// adding externals
webpackConfig.externals = [
'#test-app/mf-example',
];
return webpackConfig;
},
} as WebpackOptions,
// Adding Server
devServer: ((devServerConfig) => {
// devServerConfig.injectClient = false;
devServerConfig.proxy = {
...devServerConfig.proxy,
'/mf-example': {
target: process.env.MF_EXAMPLE,
secure: false,
changeOrigin: true,
}
};
return devServerConfig;
}) as DevServerOptions,
};
Btw, the problem is not related to other files or configs so i did not share them.

import "!babel-loader!mdx-loader!foo.mdx" not working with react-scripts#5.0.0

Trying to upgrade an existing React project from react-scripts#4 to #5.0.0 fails for importing transpiled MDX sources.
/* eslint import/no-webpack-loader-syntax: off */
import AboutMDX from "!babel-loader!mdx-loader!./About.mdx"
AboutMDX does not receive an MDXComponent but instead now as of react-scripts 5 end up with a string which is the path name of the transpiled javascript source code file. How can I fix this change in behavior to correctly import the MDXComponent?
This has been an od(d)ysee because the whole MDX2+CRA5+remark/rehype ecosystem is prone to breakage in my experience. While MDX documents to use CRACO7 with CRA5, the MDX project when kindly asked points fingers to CRACO and wasn't helpful to me in getting me over ES modules and CSJ hurdles in order to finally get the pieces to work. While the following now works for me (at the moment) I don't know how robust this set up actually is.
upgrade to CRA 5
install CRACO 5
make sure to call the craco command instead of react in your package.json scripts.
make sure to clean up your (stale) dependencies.
add these dependencies and dev dependencies:
"#mdx-js/loader": "^2.2.1",
"#mdx-js/mdx": "^2.2.1",
"#mdx-js/react": "^2.2.1",
"#types/mdx": "^2.0.3",
"#craco/craco": "^7.0.0",
"#craco/types": "^7.0.0",
if in the past you had a declare module '*.mdx {...}' in a src/index.d.ts then remove this now completely, as it would conflict with what comes with the MDXv2 loader.
remove !babel-loader!mdx-loader! from all your *.mdx imports. Do not use !#mdx-js/loader! etc. either, as the webpack configuration below will take care of the preprocessing.
create a craco.config.js as follows; this is a more elaborate configuration that shows how to actually pull in ES modules with CRACO 5 still not supporting ESM in their configuration, but requiring to go through the dynamic import with delayed configuration setup hurdles:
const { addAfterLoader, loaderByName } = require('#craco/craco')
module.exports = async (env) => {
const remarkGfm = (await import('remark-gfm')).default
const remarkImages = (await import('remark-images')).default
const remarkTextr = (await import('remark-textr')).default
const rehypeSlug = (await import('rehype-slug')).default
const textrTypoApos = (await import('typographic-apostrophes')).default
const textrTypoQuotes = (await import('typographic-quotes')).default
const textrTypoPossPluralsApos = (await import('typographic-apostrophes-for-possessive-plurals')).default
const textrTypoEllipses = (await import('typographic-ellipses')).default
const textrTypoEmDashes = (await import('typographic-em-dashes')).default
const textrTypoEnDashes = (await import('typographic-en-dashes')).default
return {
webpack: {
configure: (webpackConfig) => {
addAfterLoader(webpackConfig, loaderByName('babel-loader'), {
test: /\.(md|mdx)$/,
loader: require.resolve('#mdx-js/loader'),
/** #type {import('#mdx-js/loader').Options} */
options: {
remarkPlugins: [
remarkGfm,
remarkImages,
[remarkTextr, {
plugins: [
textrTypoApos,
textrTypoQuotes,
textrTypoPossPluralsApos,
textrTypoEllipses,
// textrTypoEmDashes,
textrTypoEnDashes,
],
options: {
locale: 'en-us'
}
}],
],
rehypePlugins: [
rehypeSlug,
],
}
})
return webpackConfig
}
}
}
}

Customize Ant design with Next.js

I am using ant design in my next.js project. but I want to customize it, for example: " #primary-color: orange; "
I searched the internet and installed all the necessary npm packages, but since I have no webpack knowledge, I got different errors every time I tried. I tried many different codes in next.config.js but I got different errors for all of them. Can someone please explain to me how to do this?
here my folder tree :
and here my next.config.js file :
I would like to state in advance that I do not know anything about webpack.
const withSass = require("#zeit/next-sass");
const withLess = require("#zeit/next-less");
const withCSS = require("#zeit/next-css");
const isProd = process.env.NODE_ENV === "production";
// fix: prevents error when .less files are required by node
if (typeof require !== "undefined") {
require.extensions[".less"] = (file) => {};
}
module.exports = withCSS({
cssModules: true,
cssLoaderOptions: {
importLoaders: 1,
localIdentName: "[local]___[hash:base64:5]",
},
...withLess(
withSass({
lessLoaderOptions: {
javascriptEnabled: true,
},
})
),
});
and here my error :
yarn run v1.22.17
warning ../../../package.json: No license field
$ next dev
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
Warning: Built-in CSS support is being disabled due to custom CSS configuration being detected.
See here for more info: https://nextjs.org/docs/messages/built-in-css-disabled
TypeError: Cannot set properties of undefined (setting 'styles')
at module.exports (/Users/hashim/Desktop/bakucosy/bakucosy-app/node_modules/#zeit/next-css/css-loader-config.js:25:56)
at Object.webpack (/Users/hashim/Desktop/bakucosy/bakucosy-app/node_modules/#zeit/next-css/index.js:15:36)
at Object.getBaseWebpackConfig [as default] (/Users/hashim/Desktop/bakucosy/bakucosy-app/node_modules/next/dist/build/webpack-config.js:1379:32)
at async Promise.all (index 0)
at async Span.traceAsyncFn (/Users/hashim/Desktop/bakucosy/bakucosy-app/node_modules/next/dist/trace/trace.js:74:20)
at async Span.traceAsyncFn (/Users/hashim/Desktop/bakucosy/bakucosy-app/node_modules/next/dist/trace/trace.js:74:20)
at async HotReloader.start (/Users/hashim/Desktop/bakucosy/bakucosy-app/node_modules/next/dist/server/dev/hot-reloader.js:325:25)
at async DevServer.prepare (/Users/hashim/Desktop/bakucosy/bakucosy-app/node_modules/next/dist/server/dev/next-dev-server.js:290:9)
at async /Users/hashim/Desktop/bakucosy/bakucosy-app/node_modules/next/dist/cli/next-dev.js:128:9
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
➜ bakucosy-app git:(master) ✗

Storybook 6, use module paths?

Is it possible to configure storybook 6 to use the module paths in my tsconfig.json file to work with sass-loader (or just to replicate the same pattern if that's not possible).
Ideally, I'd like to be able to add a sass loader with this option:
additionalData: `
#use '#themes' as vars;
#use '#themes/breakpoints' as bp;
`,
instead of
additionalData: `
#use '../themes' as vars;
#use '../themes/breakpoints' as bp;
`,
My tsconfig.json file has this section in it which works well inside .ts files but obviously doesn't work in sass files:
"paths": {
"#components/*": ["./components/*"]
}
If I could replicate that for themes, that'd be amazing.
Turns out it was pretty easy:
in main.js. Add the following to your module.exports:
webpackFinal: async (config, { configType }) => {
config.resolve.alias = {
...config.resolve.alias,
"#themes": path.resolve(__dirname, "../themes/default")
}
return config;
}
Actually, past Alex, there is a better solution now using the ts-config-paths-webpack-plugin that is automatic and doesn't require repeating config code:
// main.js
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const pathsPlugin = new TsconfigPathsPlugin({
configFile: path.resolve(__dirname, '../tsconfig.json')
})
webpackFinal: async (config) => {
if (config.resolve.plugins) {
config.resolve.plugins.push(pathsPlugin);
} else {
config.resolve.plugins = [pathsPlugin];
}
...

Resources