Configuring Vanilla TS Vite project to keep CSS files separated - css

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 !

Related

NextJS images are not shown using "export" script

I have a simple NextJs app.
When I'm running the app on a localhost everything seems to work fine - All the images are shown as expected
When I use this script: next build && next export
and browse to my local build, I don't see the images, but instead its "alt" text
The way I import an image:
import React from 'react';
import Image from 'next/image';
import someImage from '../../../public/images/some-image.png';
const Main = () => {
return (
<div>
<Image
src={someImage}
alt="Some Image"
placeholder="blur"
/>
</div>
}
next.config.js
/** #type {import('next').NextConfig} */
const configuration = {
reactStrictMode: true,
eslint: {
dirs: ['./src'],
ignoreDuringBuilds: true,
},
images: {
loader: 'akamai',
path: '',
},
};
module.exports = configuration;
My code design:
Environment:
"next": "13.1.6",
"react": "18.2.0",
Moreover, I tried to use a normal img tag and it causes the same problem.
If anyone here faces the same issue ill appreciate any help!
Refer to this page:
https://nextjs.org/docs/messages/export-image-api
You are attempting to run next export while importing the next/image component using the default loader configuration.
However, the default loader relies on the Image Optimization API which is not available for exported applications.
So, when running static NextJS app with export you cannot use NextJS optimization, as it should run in your non-existent server. You should use cloud solution (https://nextjs.org/docs/api-reference/next/image#loader-configuration) or remove optimization:
module.exports = {
images: {
unoptimized: true,
},
}
(https://nextjs.org/docs/api-reference/next/image#unoptimized)
When importing something statically from the public folder it already knows youre inside it. You only need the following import:
import someImage from 'images/some-image.png';

Nuxt 3 / Vuetify 3 - How to import Material Icons?

I am trying to setup Material Design Icons, and I have the following config:
nuxt.config.ts
import { defineNuxtConfig } from 'nuxt';
export default defineNuxtConfig({
modules: ['#nuxtjs/tailwindcss'],
css: ['vuetify/lib/styles/main.sass', '#mdi/font/css/materialdesignicons.min.css'],
build: {
transpile: ['vuetify'],
},
vite: {
define: {
'process.env.DEBUG': false,
},
},
})`
```
But in terminal I am keep getting the same message whatever I try
[Vue Router warn]: No match found for location with path "/materialdesignicons.min.css.map"
I installed #mdi/font package and followed the vuetify3 official docs but no success.
Also, I have installed Nuxt 3 and Vuetify 3, and dev dependencies sass-loader and sass.
Icons are shown, no problems with display in <v-icon> tag but in terminal I keep getting the same error message.
I have been Googling a lot but I can't seem to find the answer.
Any ideas? Thanks
You need to tell vuetify to use the material icons as icon pack in your plugins/vuetify.ts.
To do so you have to install the mdi font, as you already did, and then set it in the vuetify icons Object in your defineNuxtPlugin.
When done, it should look like this:
import { createVuetify } from 'vuetify'
import {aliases, mdi} from "vuetify/lib/iconsets/mdi";
// make sure to also import the coresponding css
import '#mdi/font/css/materialdesignicons.css' // Ensure you are using css-loader
// Ensure your project is capable of handling css files
export default defineNuxtPlugin(nuxtApp => {
const vuetify = createVuetify({ // Replaces new Vuetify(...)
theme: {
defaultTheme: 'dark'
},
icons: {
defaultSet: 'mdi',
aliases,
sets: {
mdi
}
},
})
nuxtApp.vueApp.use(vuetify)
})
You can then simply use it like this:
<v-icon icon="mdi-minus" />
For a more detailed explanation, visit This Article
I just import materialdesignicons to plugins/vuetify.ts. It works for me.
first install "#mdi/font" and then use this config:
// plugins/vuetify.ts
import { createVuetify } from "vuetify";
import "#mdi/font/css/materialdesignicons.css";
export default defineNuxtPlugin((nuxtApp) => {
const vuetify = createVuetify({
ssr: true,
theme: {
defaultTheme: "light",
},
});
nuxtApp.vueApp.use(vuetify);
});

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 !.

Trouble adding Bootstrap 4 CSS with Webpack 4 in ReactJS SpringBoot Application

I am getting an error where webpack is not able to resolve the bootstrap 4 css which is sitting in the node_modules directory. I have looked at a number of tutorials around webpack 4 and bootstrap 4 but I am thinking it is not in the same folder structure.
I've also tried changing the import bootstrap css trying to change the directory to push it to the node_modules directory but that does not seem to work.
Error log from Spring Tool Suite
[INFO] ERROR in ./src/main/resources/static/js/app.js
[INFO] Module not found: Error: Can't resolve 'bootstrap/dist/css/boostrap.min.css' in 'C:\sourcecode\personal-website\src\main\resources\static\js'
[INFO] # ./src/main/resources/static/js/app.js 26:0-46
webpack.config.js
var path = require('path');
module.exports = {
entry: './src/main/resources/static/js/app.js',
performance: {
hints: false
},
output: {
path: __dirname,
filename: './src/main/resources/static/built/bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
loader: 'babel-loader',
query: {
presets: ['#babel/react', '#babel/env']
}
},
{
test: /\.css$/,
include: /stylesheets|node_modules/,
use: [ "style-loader", "css-loader" ]
}
]
}
};
app.js
import 'bootstrap';
import React from 'react';
import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/boostrap.min.css';
import Landing from './components/Landing';
class App extends React.Component {
render() {
return (
<div className="container">
<Landing />
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('react-app')
);
I'm not sure what your folder structure is like. But, I believe everything is relative to the location of the file where you're importing bootstrap's css from.
Given the folder structure below
sourceCode
|--node_modules
|--bootstrap
|--dist
|--css
|--bootstrap.min.css
|--routes
|--src
|--main
|--resources
|--static
|--app.js
|--dist
|--views
if you're importing bootstrap's CSS stylesheet in the app.js script, it would go like:
import '../../../../node_modules/bootstrap/dist/css/bootstrap-min.css';
The double period (..) means you're moving one step up the folder structure/tree.
You did say you've tried changing your import. But, I based my answer on what you've shown.
On the other hand, try taking a look at VS Code then check out the Path Intellisense extension. It'll help you with those imports. Happy coding :)

How to use css #import in rollup?

I try to create a simple rollup app's config and have some troubles with css.
This is my css file:
#import "normalize.css";
#import "typeface-roboto";
html, body, #root {
height: 100%;
font-family: Roboto, serif;
}
body {
background: url('./images/background.jpg');
}
And all what i have is 3 errors about not found resources.
This is my config file:
import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
import babel from 'rollup-plugin-babel'
import replace from 'rollup-plugin-replace'
import postcss from 'rollup-plugin-postcss'
import html from 'rollup-plugin-fill-html'
import url from "rollup-plugin-url"
process.env.NODE_ENV = 'development'
const CWD = process.cwd()
const Paths = {
SRC: `${CWD}/src`,
DIST: `${CWD}/dist-rollup`,
NODE_MODULES: `${CWD}/node_modules`
}
Object.assign(Paths, {
INPUT: Paths.SRC + '/index.js',
OUTPUT: Paths.DIST + '/index.js'
})
export default {
input: Paths.INPUT,
output: {
file: Paths.OUTPUT,
format: 'iife', // immediately-invoked function expression — suitable for <script> tags
// sourcemap: true
},
plugins: [
html({
template: `${Paths.SRC}/template.html`,
filename: 'index.html'
}),
postcss({
modules: true,
plugins: [
]
}),
url({
limit: 10 * 1024, // inline files < 10k, copy files > 10k
}),
resolve(), // tells Rollup how to find date-fns in node_modules
babel({
exclude: 'node_modules/**'
}),
commonjs(), // converts date-fns to ES modules
replace({ 'process.env.NODE_ENV': JSON.stringify('development') })
]
}
I was tried to use some plugins like rollup-plugin-rebase and postcss-assets, but unfortunately, it did not help me.
Maybe i chose not common way, but single working solution for me is use postcss with 2 plugins: postcss-imports for #import syntax and postcss-url for url.
But there were difficulties too.
Postcss-url don't want just work, like i expect.
I had to use 3 instance of this plugin:
[
postcssUrl(), // Find files' real paths.
postcssUrl({
url: 'copy',
basePath: 'src',
useHash: true,
assetsPath: 'dist'
}), // Copy to required destination.
postcssUrl({
url (asset) {
const rebasedUrl = `dist/${path.basename(asset.absolutePath)}`
return `${rebasedUrl}${asset.search}${asset.hash}`
}
}) // Fix final paths.
]
You may see it in complex on https://github.com/pashaigood/bundlers-comparison
And of course, i will be glad to see more simple solution if you know that, please, share with me.
I've found css-import to work well, the NPM package provides a cssimport command line interface that accepts a main CSS file which includes #import statements and an optional list of directory in which to search for the CSS; it outputs to stdout the merged CSS which can be written to a single file.
I use the following to output a single main.css file in my build directory, searching for imported files under node_modules:
cssimport main.css ./node_modules/ > ./build/main.css
When using rollup you can use the rollup-plugin-execute plugin to execute a shell command as part of rollup's build process. For example:
plugins: [
...
execute('npx cssimport main.css ./node_modules/ > build/main.css')
]

Resources