I have created a library in angular which is styled using tailwind. This is then been push to NPM and then imported into a new project, but the css is not getting applied. I have referenced the node-module path in my tailwind.config.ts:
content: [
"./src/**/*.{html,ts}",
'./node_modules/components-name/**/*.{html,js,ts}'
],
What am i missing?
Tailwind is working if i apply it directly to the new application, it just doesn't work with the imported library.
If you expect all depender apps to utilize tailwind, you can use tailwind classes in your library HTML and have them configure a content path of ./node_modules/my-lib/esm2020/**/*.mjs.
It finds the inlined/escaped classes in the Ivy compiled files.
esm2020 to scope the scan.
Update 11/30/22 - allowing the use of #apply in the library
#applys are not resolved in precompiled library code as these files are not processed in that lifecycle.
As a workaround, you can pre-process your components to resolve #apply styles before building the library.
Create a tailwind.config.js to use in the compilation
If your library project has a demo-app (highly suggest for impl testing), could utilize it's config file, unless you've got some crazy config in there. Since we're not rendering #tailwind components or anything, we won't get any excess styles
projects/my-lib/tailwind.config.js
module.exports = {
content: [
'./projects/my-lib/**/*.{html,ts,css,scss}',
],
};
Note the content path is still relative from project root as that's the context it's ran at
Create precompiler process
Tailwind resolve into a new file (mostly so we don't mess things up accidentally locally)
Point component at the new file
import { readFile, writeFile } from "fs";
import { sync } from 'glob';
import { exec } from 'child_process';
const libRoot = 'projects/my-lib/src/lib';
const tailwindConf = 'tailwind.config.js'; // may be apps/demo when using NX
const processedExt = '.precompiled.scss';
const styleRegex = /styleUrls:\s*\[([^\]]+)]/;
// Find all `.scss` files and tailwind process them
sync(`${libRoot}/**/*.component.scss`).forEach(file => {
const cssFile = file.replace(/\.scss$/, processedExt);
exec(`npx tailwind -c ${tailwindConf} -i ${file} -o ${cssFile}`, (err, stdout, stderr) => {
if (err) {
console.error(stderr);
throw err;
}
});
});
// .component.ts update
// Find all components with `styleUrls` and switch `.scss` extension to our precompiled file names
sync(`${libRoot}/**/*.component.ts`).forEach(file => {
readFile(file, (err, data) => {
if (err) throw err;
const content = data.toString();
const match = content.match(styleRegex);
if (match) {
const styleUrls = match[1]
.split(',')
.map(s => s.trim().replace('.scss', processedExt))
.join(', ');
writeFile(file, content.replace(styleRegex, `styleUrls: [${styleUrls}]`), (err) => {
if (err) throw err;
});
}
});
});
This should only be ran by your CI process and never committed.
Also this could easily be switched to javascript instead of typescript
Other possible ways to do this (untested) without the .component.ts update:
Utilize environment.prod.ts's production: true flag to decide the style file to use
styleUrls: [ environment.prod ? 'my.component.precompiled.scss' : 'my.component.scss' ],
Gotta remember this for all new components
Change the tailwind compile to output to the same scss file
Less moving parts - I liked the separate file so I'd realize quickly if it were accidentally ran/committed
Add CI precompile command to package.json
"build:ci": "node --require ts-node/register projects/my-lib/src/precompile.ts && npm run build:my-lib"
Very rough implementation - remove --require ts-node/register if converted to javascript
I use NX workspace, so I added a new target in the library's project.json:
"ci": {
"executor": "nx:run-commands",
"options": {
"command": "node --require ts-node/register libs/my-lib/src/precompile.ts"
}
},
and added a the package.json entry as:
"build": "nx run-many --all --target build",
"build:ci": "npx nx ci && npm run build",
allowing build to still be used locally.
Build and Package/Release as normal
With #apply's resolved, all should flow well
If you used tailwind utility classes in HTML, be sure to see the very beginning of this answer
Tailwindless Depender
If you want applications to be able to utilize your library without them installing tailwind you could supply a stylesheet containing all the helper classes you used.
Create a stylesheet to contain all used utilities
projects/my-lib/style.scss
#tailwind utilities;
Add a postbuild to your package.json to produce the stylesheet, assuming you use npm run build to build the library.
"postbuild": "npx tailwind -c projects/my-lib/tailwind.config.js -i projects/my-lib/style.scss -o dist/my-lib/style.scss",
Direct depender projects to then include this compiled stylesheet:
#import 'my-lib/style.scss'
Note tailwind does not compile SCSS into CSS - need to run through a SASS processor if you want to supply CSS.
Downside of this is all utility classes used in all components are produced, even if the depender app doesn't use them (same happens for projects using tailwind, so not so bad).
Also the depender project may produce duplicate utility classes if using tailwind itself.
Plus side is your library doesn't require the depender to have tailwind.
Note that you still need the above process to resolve #apply's - this only gathers the utility classes used in the HTML
Related
I'm trying to run a completely separate css/sass build to a specific file.
So I have a folder in my src like:
/src
/sass
./index.sass
./btn.sass
./etc.sass
I'm trying to get it to output to a specific file like "build.css" or whatever which would just end up in the default build directory of "dist" as "dist/build.css".
Been trying to play with vue.config.js and chainWebpack but totally lost here.
Any suggestions how to accomplish this?
One way to do this is to add a Webpack entry that points to the Sass file you want to bundle (using configureWebpack.entry):
// vue.config.js
const { defineConfig } = require('#vue/cli-service')
module.exports = defineConfig({
⋮
configureWebpack: {
entry: {
app: './src/main.js',
extCss: './src/sass/index.sass', 👈
},
},
})
This has a downside as it also generates a .js file that is effectively a no-op. You'd have to delete that manually as a cleanup step:
dist/css/app.css
dist/css/extCss.css # CSS bundle of Sass output
dist/js/app.js
dist/js/chunk-vendors.js
dist/js/extCss.js # no-op file (delete me)
Also delete the <script src="/js/extCss.js"></script> from dist/index.html.
I have successfully set up #poppanator/sveltekit-svg with SvelteKit using the following configuration (svelte.config.js):
import preprocess from 'svelte-preprocess';
import svg from '#poppanator/sveltekit-svg';
/** #type {import('#sveltejs/kit').Config} */
const config = {
// Consult https://github.com/sveltejs/svelte-preprocess
// for more information about preprocessors
preprocess: preprocess(),
kit: {
// hydrate the <div id="svelte"> element in src/app.html
target: '#svelte',
vite: {
plugins: [svg()]
}
}
};
export default config;
This works when running the SvelteKit project using npm run dev. However, I cannot get the svg plugin to work inside Storybook.
I have the following Storybook configuration (.storybook/main.cjs):
module.exports = {
"stories": [
"../src/**/*.stories.mdx",
"../src/**/*.stories.#(js|jsx|ts|tsx|svelte)"
],
"addons": [
"#storybook/addon-links",
"#storybook/addon-essentials",
"#storybook/addon-svelte-csf"
],
"core": {
"builder": "storybook-builder-vite"
},
"svelteOptions": {
preprocess: import("../svelte.config.js").preprocess
}
}
When importing SVG files in Storybook stories (or in components used by the stories), only the file path of the SVG file is returned. When importing SVG files inside a SvelteKit route, a Svelte component is returned as it should be.
I have tried this with Storybook 6.3.10 and 6.4.0-beta.7 with storybook-builder-vite (0.1.0).
How should this go together to make SVG imports work inside Storybook?
While SvelteKit uses Vite, Storybook uses Webpack.
To get svg imports working you'll need to find a loader for webpack that behaves similar to the #poppanator/sveltekit-svg plugin and add that to your storybook configuration.
I'm not sure similar loader exists (yet), depending on your usage, renaming the .svg files to .svelte could be an alternative
I am trying to import "../../node_modules/react-quill/dist/quill.snow.css"; in my next.js project but I get following error
[ error ] ./node_modules/react-quill/dist/quill.snow.css
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
Location: components\crud\BlogCreate.js
I managed to make it work with next.config.js. It worked with this configuration
// next.config.js
const withCSS = require('#zeit/next-css');
module.exports = withCSS({
cssLoaderOptions: {
url: false
}
});
But now I am getting a warning,
Warning: Built-in CSS support is being disabled due to custom CSS configuration being detected.
See here for more info: https://err.sh/next.js/built-in-css-disabled
It seems my solution is not the best way to solve this problem. How could I get rid of this warning?
You may remove the #zeit/next-css plugin because the Next.js 9.3 is very simple. Then Next.js 9.3 is Built-in Sass Support for Global Stylesheets after removing the #zeit/next-css you may install
npm install sass
Then, import the Sass file within pages/_app.js.
Global CSS
Import any global CSS in the /pages/_app.js.
import '../styles.css'
// This default export is required in a new `pages/_app.js` file.
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
Importing CSS in components or pages won't work with the built-in CSS support.
Component CSS
Next.js supports CSS Modules using the [name].module.css file naming convention.
components/Button.module.css
/*
You do not need to worry about .error {} colliding with any other `.css` or
`.module.css` files!
*/
.error {
color: white;
background-color: red;
}
components/Button.js
import styles from './Button.module.css'
export function Button() {
return (
<button
type="button"
// Note how the "error" class is accessed as a property on the imported
// `styles` object.
className={styles.error}
>
Destroy
</button>
)
}
CSS Module files can be imported anywhere in your application.
Third-party CSS on Component / Page level
You can use <link> tag in the component.
const Foo = () => (
<div>
<link
href="third.party.css"
rel="stylesheet"
/>
</div>
);
export default Foo;
The loaded stylesheet won't be automatically minified as it doesn't go through build process, so use the minified version.
If none of the options doesn't fit your requirements consider using a custom CSS loader like #zeit/next-css.
In that case you will see a warning which is fine:
Warning: Built-in CSS support is being disabled due to custom CSS configuration being detected.
See here for more info: https://err.sh/next.js/built-in-css-disabled
Suggested reading:
Next.js Built-In CSS Support
Global SASS
CSS Modules
Install sass module by running following command.
npm install sass
You then need to remove all css-loader and sass-loader configuration from next.config.js.
For example, I had to remove the withSass() function (in your case withCSS()) and just return the configuration object.
Had to remove the following lines from next.config.js
{
test: /\.scss$/,
use: {
loader: "sass-loader",
options: {
data: '#import "./scss/_variables.scss"',
sourceMap: true,
},
},
}
Move your options to sassOptions in next config file.
sassOptions: {
data: '#import "./scss/_variables.scss"',
sourceMap: true,
}
Also remove the old #zeit/next-sass and #zeit/next-css from package.json
I had to remove following #zeit dependency from my package.json
"dependencies": {
"#zeit/next-sass": "1.0.1",
This worked for me.
For more details, visit https://nextjs.org/docs/basic-features/built-in-css-support
How do I correctly import a non-plugin npm module into Ember?
I'm trying to use the sass version of flag-icon-css with ember-cli so that the sass is being built during deploy with the rest of ember-cli-sass, but I can't figure out how to do it in an automated fashion (e.g. without manually copying files over to public).
Using ember-auto-import seems like a good place to start but it is more tailored towards javascript imports.
I have tried this configuration in ember-cli-build.js:
'sassOptions': {
includePaths: [
'node_modules/flag-icon-css/sass' // flag-icon.scss
]
},
It will add the styles, but it doesn't include the images used in the styles.
I have read this documentation, but it doesn't specify something more complicated than a single file.
Just use ember-cli-sass:
first add it to includePaths in your ember-cli-build.js
new EmberApp({
sassOptions: {
includePaths: [
'node_modules/flag-icon-css/sass'
]
}
});
use it with #import "flag-icon";
Have a look in the readme.
now while this will sucessfully add the compiled sass output to your /assets/app-name.js there is no automated way to add any kind of assets to your dist folder.
In the case of flag-icon-css it will just add background-image: url(../flags/4x3/gr.svg); to your dist/assets/app-name.css, but not add the svg itself. You can manually do this with broccolis Funnel and MergeTrees:
install broccoli-funnnel and broccoli-merge-trees
import them in ember-cli-build.js:
const Funnel = require('broccoli-funnel');
const MergeTrees = require('broccoli-merge-trees');
use them by replacing return app.toTree() in your ember-cli-build.js with
const flagIcons = Funnel('node_modules/flag-icon-css', { include: ['flags/**/*'] });
return new MergeTrees([app.toTree(), flagIcons]);
so your entire ember-cli-build.js could look like this:
'use strict';
const EmberApp = require('ember-cli/lib/broccoli/ember-app');
const Funnel = require('broccoli-funnel');
const MergeTrees = require('broccoli-merge-trees');
module.exports = function(defaults) {
let app = new EmberApp(defaults, {
// Add options here
sassOptions: {
includePaths: [
'node_modules/flag-icon-css/sass'
]
}
});
const flagIcons = Funnel('node_modules/flag-icon-css', { include: ['flags/**/*'] });
return new MergeTrees([app.toTree(), flagIcons]);
};
a short sidenote: I would usually recommend to put assets into the assets folder of your output, but in this case this wont work because the flag-icon-css expects the flags folder to be in the parent directory of the .css.
I figured this out, but I'm not sure it's the best or easiest way. It has some drawbacks.
const EmberApp = require('ember-cli/lib/broccoli/ember-app')
const Funnel = require('broccoli-funnel')
module.exports = function(defaults) {
const app = new EmberApp(defaults, {
'sassOptions': {
includePaths: [
'node_modules/flag-icon-css/sass'
]
}
})
const flags = new Funnel('node_modules/flag-icon-css/', {
srcDir: 'flags',
destDir: '/flags',
})
return app.toTree([flags])
}
The drawback is that the css image urls are not processed, and hardlinked to ../flags, so I have to funnel them into /flags, which is not the convention, as these assets should be compiled into public/assets/images.
This is a two-step implementation (or more steps if the npm module would be more complex). It would be preferred to include just the scss and have (an) Ember (plugin) automatically fetch the dependent resources.
I'm using Webpack with the extract-text-webpack-plugin.
In my project, I have some build scripts. One of the build scripts is supposed to bundle and minify CSS only. As I'm using Webpack for the other scripts, I found it a good idea to use Webpack even when I only want to bundle and minify CSS.
It's working fine, except that I can't get rid of the output.js file. I don't want the resulting webpack output file. I just want the CSS for this particular script.
Is there a way to get rid of the resulting JS? If not, do you suggest any other tool specific for handling CSS? Thanks.
There is an easy way, no extra tool is required.
There is an easy way and you don't need extra libraries except which you are already using: webpack with the extract-text-webpack-plugin.
In short:
Make the output js and css file have identical name, then the css file will override js file.
A real example (webpack 2.x):
import path from 'path'
import ExtractTextPlugin from 'extract-text-webpack-plugin'
const config = {
target: 'web',
entry: {
'one': './src/one.css',
'two': './src/two.css'
},
output: {
path: path.join(__dirname, './dist/'),
filename: '[name].css' // output js file name is identical to css file name
},
module: {
rules: [
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader'
})
}
]
},
plugins: [
new ExtractTextPlugin('[name].css') // css file will override generated js file
]
}
Unfortunately, that is currently not possible by design. webpack started as a JavaScript bundler which is capable of handling other "web modules", such as CSS and HTML. JavaScript is chosen as base language, because it can host all the other languages simply as strings. The extract-text-webpack-plugin is just extracting these strings as standalone file (thus the name).
You're probably better off with PostCSS which provides various plugins to post-process CSS effectively.
One solution is to execute webpack with the Node API and control the output with the memory-fs option. Just tell it to ignore the resulting js-file. Set the output.path to "/" in webpackConfig.
var compiler = webpack(webpackConfig);
var mfs = new MemoryFS();
compiler.outputFileSystem = mfs;
compiler.run(function(err, stats) {
if(stats.hasErrors()) { throw(stats.toString()); }
mfs.readdirSync("/").forEach(function (f) {
if(f === ("app.js")) { return; } // ignore js-file
fs.writeFileSync(destination + f, mfs.readFileSync("/" + f));
})
});
You can clean up your dist folder for any unwanted assets after the done is triggered. This can be easily achieved with the event-hooks-webpack-plugin
//
plugins: [
new EventHooksPlugin({
'done': () => {
// delete unwanted assets
}
})
]
Good Luck...