React imported css not available - css

I'm trying to implement react-component/time-picker in a component of mine.
The imports seem to "work", but the component is not getting the styles it needs.
import TimePicker from 'rc-time-picker'
import 'rc-time-picker/assets/index.css'
I've dug around in the source files and found the message below that the css was "removed by extract-text-webpack-plugin". I don't know if this is normal or the cause of my problems.
/*!******************************************************!*\
!*** ./node_modules/rc-time-picker/assets/index.css ***!
\******************************************************/
/*! dynamic exports provided */
/***/ (function(module, exports) {
// removed by extract-text-webpack-plugin
I'm not a react expert, and the React app was set up via Rails / Webpacker by someone who has left the company.
I've found the the css is getting compiled fine into public/bundle-c9134289a37e525df9bab3bda8e77e4f.css without error.
So, my issue is that the CSS doesn't seem to be available on my page. I don't understand where imported CSS is supposed to go and how is it controlled? But, it seems like this CSS isn't going there.
Am I missing something obvious?
Edit 1:
config/webpack/loaders/less.js
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
test: /\.less$/,
use: ExtractTextPlugin.extract({
use: ['css-loader', 'less-loader']
})
}
config/webpack/environment.js
const { environment } = require('#rails/webpacker')
const less = require('./loaders/less')
environment.loaders.append('less', less)
module.exports = environment

Try adding
import 'rc-time-picker/assets/index.css'
To your app/javascript/packs/application.js file
Docs: rails/webpacker CSS, Sass, SCSS

Try this:
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractCSS = new ExtractTextPlugin('yourfile.min.css');
module.exports = {
test: /\.less$/,
use: extractCSS.extract({
use: ['css-loader', 'less-loader']
})
}

Related

Configuring Vanilla TS Vite project to keep CSS files separated

I am trying to set up a basic (css) library with vanilla TS and Vite 4.
I want to have a main js and css file at the top level so you can import the whole thing in one go. I also want to have component level imports where you can chose to just import the components js + css. The combined css and JS files are working fine; and the individual component JS file is working fine too.
Currently I'm running into the problem where I can't seem to keep an isolated version of the CSS files next to the JS files after bundling. My build is currently creating :
I've gone over the docs of both Vite and Rollup but I can't seem to figure out how to do the same to my CSS as I'm doing to my JS.
dist
--components
----button
------button.js
--main.css
--main.js
My preferred output would be:
dist
--components
----button
------button.js
------button.css
--main.css
--main.js
In my `main.ts` I'm importing:
import './style.scss'
import './tokens.scss'
import './components/button/button.scss'
vite.config.js
import { defineConfig } from 'vite'
import { resolve } from 'path'
export default defineConfig({
build: {
cssCodeSplit: false,
manifest: true,
rollupOptions: {
output: {
assetFileNames: () => 'main[extname]',
}
},
lib: {
formats: ['es'],
entry: {
main: resolve(__dirname, 'src/main.ts'),
button: resolve(__dirname, 'src/components/button/button.ts')
},
name: 'CSSFramework',
fileName: (_, fileName) => fileName === 'main' ? '[name].js' : 'components/[name]/[name].js',
},
},
});
Thanks in advance !

Using vite plugins with Storybook and SvelteKit

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

Next.js Global CSS cannot be imported from files other than your Custom <App>

My React App was working fine, using global CSS also.
I ran npm i next-images, added an image, edited the next.config.js, ran npm run dev, and now I'm getting this message
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
I've checked the docs, but I find the instructions a little confusing as I am new to React.
Also, why would this error happen now? Do you think it has anything to do with the npm install?
I've tried to remove new files I've added along with their code, but this doesn't fix the problem. I've also tried what the Read more: suggests.
My highest tier component.
import Navbar from './Navbar';
import Head from 'next/head';
import '../global-styles/main.scss';
const Layout = (props) => (
<div>
<Head>
<title>Bitcoin Watcher</title>
</Head>
<Navbar />
<div className="marginsContainer">
{props.children}
</div>
</div>
);
export default Layout;
My next.config.js
// next.config.js
const withSass = require('#zeit/next-sass')
module.exports = withSass({
cssModules: true
})
My main.scss file
#import './fonts.scss';
#import './variables.scss';
#import './global.scss';
my global.scss
body {
margin: 0;
}
:global {
.marginsContainer {
width: 90%;
margin: auto;
}
}
The thing I find the weirdest is that this error came without changing anything to do with CSS, or Layout.js, and it was previously working?
I've moved my main.scss import to the pages/_app.js page, but the styles still aren't coming through. This is what the _app.js page looks like
import '../global-styles/main.scss'
export default function MyApp({ Component, props }) {
return <Component {...props} />
}
Use the built-in Next.js CSS loader (see here)
instead of legacy #zeit/next-sass.
Replace #zeit/next-sass package with sass.
Remove next.config.js. Or do not change CSS loading in it.
Move the global CSS as suggested in the error message.
Since Next.js 9.2 global CSS must be imported in Custom <App> component.
// pages/_app.js
import '../global-styles/main.scss'
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
To add styles only to a specific component or page you can use built-in support of CSS modules. (see here)
For example, if you have a component Button.js you can create a Sass file button.module.scss and include it in the component.
Next.js stops complaining when your file has module in naming, e.g., changing import '../global-styles/main.scss'; to import '../global-styles/main.module.scss'; would fix the warning and you could have your styles in the global-styles, or for example, in your component.
No extra dependencies/configurations in next.config.js is required.
You can replace the opinionated (and overly-complex?) NextJs CSS loaders with your own. Here's a simple one for global css:
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
reactStrictMode: true,
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
// Find and remove NextJS css rules.
const cssRulesIdx = config.module.rules.findIndex(r => r.oneOf)
if (cssRulesIdx === -1) {
throw new Error('Could not find NextJS CSS rule to overwrite.')
}
config.module.rules.splice(cssRulesIdx, 1)
// Add a simpler rule for global css anywhere.
config.plugins.push(
new MiniCssExtractPlugin({
experimentalUseImportModule: true,
filename: 'static/css/[contenthash].css',
chunkFilename: 'static/css/[contenthash].css',
})
)
config.module.rules.push({
test: /\.css$/i,
use: !isServer ? ['style-loader', 'css-loader'] : [MiniCssExtractPlugin.loader, 'css-loader'],
})
return config
},
}
Add this to your _app.js
import '../styles/globals.css'
For me the problem was because I had used two module.exports in my next.config.js file like this
const withPlugins = require('next-compose-plugins')
const sass = require('#zeit/next-sass')
const css = require('#zeit/next-css')
const nextConfig = {
webpack: function(config){
config.module.rules.push({
test: /\.(eot|woff|woff2|ttf|svg|png|jpg|gif)$/,
use: {
loader: 'url-loader',
options: {
limit: 100000,
name: '[name].[ext]'
}}
})
return config
}
}
module.exports = withPlugins([
[css],
[sass, {
cssModules: true
}]
], nextConfig)
module.exports = {
env: {
MONGO_URI = 'your uri'
}
}
. 1I modified it to change the export module like this.
const nextConfig = {
webpack: function(config){
config.module.rules.push({
test: /\.(eot|woff|woff2|ttf|svg|png|jpg|gif)$/,
use: {
loader: 'url-loader',
options: {
limit: 100000,
name: '[name].[ext]'
}}
})
return config
},
env: {
MONGO_URI: "your uri"
}
}
2then I deleted the second module.exports
This node package provides a perfect solution for it. You can find it here
Steps to fix it:
1. Add package:
npm install next-remove-imports
or
yarn add next-remove-imports
2. Add this wrapper variable inside your next.config.js
const removeImports = require('next-remove-imports')({
test: /node_modules([\s\S]*?)\.(tsx|ts|js|mjs|jsx)$/,
matchImports: "\\.(less|css|scss|sass|styl)$"
});
All it is doing is re-enabling global styling import rule for tsx|ts|js|mjs|jsx files
3. Wrap your next config export with this next-remove-imports wrapper. Something like this:
module.exports = removeImports((nextConfig)
4. Now restart your react app and you will be able to import CSS files inside any ts|js|js|jsx|mjs file or component.
Try to include ".module" in your scss file name.
Change main.scss to main.module.scss
Example:
import styles from './todolist-profile-info.module.scss'
You did not need to do anything inside of next.config.js.
Let's assume you are using a global css like Bootstrap, meaning it contains css that is meant to be applied to your entire application and all the different pages inside of it.
Global css files have to be wired up to NextJS in a very particular fashion.
So inside of the pages/ directory you need to create _app.js.
It's critical that the file be named _app.js.
Then at the top of that file you would import Bootstrap css in the following manner:
import 'bootstrap/dist/css/bootstrap.css';
Then you would add the following:
export default ({ Component, pageProps }) => {
return <Component {...pageProps} />;
};
So what is going on in that code?
Well, behind the scenes, whenever you try to navigate to some distinct page with NextJS, NextJS will import your component from one of the different files inside your pages/ directory.
NextJS does not just take your component and show it on the screen.
Instead it wraps it up inside of its own custom default component and that is referred to inside of NextJS as the App.
What you are doing by defining the _app.js is to define your own custom app component.
So whenever you try to visit a route inside a browser or your root route, NextJS is going to import that given component and pass it into the AppComponent as the Component prop.
So Component there is equal to whatever components you have in the pages/ directory. And then pageProps is going to be the set of components that you are intending to pass to your files inside of pages/.
So long story short, this thing is like thin wrapper around the component that you are trying to show on the screen.
Why do you have to define this at all?
Well, if you ever want to include some global css to the project, Bootstrap being a global css for example, you can only import global css into the _app.js file.
It turns out that if you try to visit other components or other pages, NextJS does not load up or even parse those files.
So any css you may have imported inside there will not be included in the final HTML file.
So you have a global css that must be included on every single page, it has to be imported into the app file because it's the only file that is guaranteed to be loaded up every single time a user goes to your application.
Don't forget that in addition to importing the css inside of _app.js, you also have to run an npm install bootstrap in your terminal.
You can read more on this here:
https://nextjs.org/docs/messages/css-global
For me, i got this error because I had used improper naming for my project's parent folder, had used special characters in it,
like project#1,
after removing special chars, and changing the folder name to like project-1, the error got away.
In my case there was typo in navbar.module.css
I've written navbar.moduile.css
you must for every component css/scss write navbar.module.css/scss/sass.Next js doesnt compile navbar.css/scss/sass. If hope my answer helps you !.

How do I import a scss npm module into Ember

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.

React with NextJS and Next-CSS: You may need an appropriate loader to handle this file type

To building a React-App i using NextJS. To use a css-file, i use the next-css plugin to do that. But when i build my App, i get the following error:
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
My next.config.js file, looks like this:
// next.config.js
const withCSS = require('#zeit/next-css')
module.exports = withCSS({
cssModules: false,
})
I importe and use a .css-file in my components as follows:
import '../style.css'
export default () => <div className="example">Hello World!</div>
My css-file Looks like this:
.example {
color: red;
}
Where is my issue? Can anyone help me to fix that?
I solved the problem. In my next.config.js i use multiple plugins. My mistake was that I had written several module.exports statements. In my case, the solution looks like this:
//next.config.js
const withImages = require('next-images');
const withCSS = require('#zeit/next-css');
module.exports = withImages(withCSS());
Try this in your next.config.js:
// next.config.js
const withCSS = require('#zeit/next-css')
module.exports = withCSS({
cssLoaderOptions: {
url: false
}
})
Now you should be able to import styleshets from node_modules like this:
import 'bootstrap-css-only/css/bootstrap.min.css';
Note: Using Next v 8+
Background:
I spent a few hours trying to simply import a CSS installed as a node_module and the various solutions are mostly hacky workarounds, but as shown above, there is a simple solution.
It was provided by one of the core team members: https://spectrum.chat/next-js/general/ignoring-folders-files-specifically-fonts~4f68cfd5-d576-46b8-adc8-86e9d7ea0b1f
I'm not sure what problem you have but I just followed the docs example:
1 Installed next-css npm install --save #zeit/next-css
2 Created next.config.js
const withCSS = require('#zeit/next-css');
module.exports = withCSS();
3 Created style.css file in the root folder
.example {
font-size: 50px;
background-color: red;
}
4 Created a test page that includes styles
import '../style.css';
export default () => <div className="example">Hello World!</div>;
and the result shows this
I have the following dependencies
"#zeit/next-css": "^1.0.1",
"next": "^7.0.0",
"react": "^16.5.2",
"react-dom": "^16.5.2"
Hope this helps you a bit!

Resources