when we try to import 3rd party libs in angular 2 cli we are using this,
var Angular2App = require('angular-cli/lib/broccoli/angular2-app');
module.exports = function(defaults) {
return new Angular2App(defaults, {
vendorNpmFiles: [
'#angular2-material/**/*.js'
]
});
};
and in system-config.ts we write it like this,
/** Map relative paths to URLs. */
const map: any = {
'#angular2-material': 'vendor/#angular2-material'
};
/** User packages configuration. */
const packages: any = {
'#angular2-material/core': {
format: 'cjs',
defaultExtension: 'js',
main: 'core.js'
},
'#angular2-material/checkbox': {
format: 'cjs',
defaultExtension: 'js',
main: 'checkbox.js'
},
// And so on...
};
and in component
import { Component } from '#angular/core';
import { MdCheckbox } from '#angular2-material/checkbox';
#Component({
selector: 'my-app',
template: `<md-checkbox></md-checkbox>`,
directives: [MdCheckbox]
})
export class AppComponent { }
all library is in .js but what if it's css how do we import it?
like how to use fontawesome , sweetalert or bootstrap ?
If you'd like to pull in a style library (bootstrap/font-awesome) you can place the files in the generated public directory.
Within there I create a style directory and place the files in there for example....
[project-root]/public/style/bootstrap.css
When builds run it will take the contents of public and move it to dist...
[project-root]/dist/style/bootstrap.css
And you can reference these files within index.html like so...
<link rel="stylesheet" href="style/bootstrap.css">
Related
So I have a default Laravel app working with Vue 3 and assets configured by Vite, TailwindCSS and TailwindUI installed. This all works fine.
I understand to have another CSS framework, I need to prefix it to avoid clashes. According to these instructions, I need to add the following line: (after installing via npm):
import PrimeVue from 'primevue/config'; //I have included this in app.js
as well as reference these styles:
primevue/resources/themes/saga-blue/theme.css
primevue/resources/primevue.min.css
primeicons/primeicons.css
How exactly do I reference these css files with a prefix so as to avoid clashes?
My postcss.config.js file currently looks like this:
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
My app.js looks like this:
import './bootstrap';
import '../css/app.css';
import { createApp, h } from 'vue';
import { createInertiaApp } from '#inertiajs/inertia-vue3';
import { InertiaProgress } from '#inertiajs/progress';
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';
import { ZiggyVue } from '../../vendor/tightenco/ziggy/dist/vue.m';
/* added by me*/ import PrimeVue from 'primevue/config';
/* added by me*/ import InputMask from 'primevue/inputmask';
const appName = window.document.getElementsByTagName('title')[0]?.innerText || 'Laravel';
createInertiaApp({
title: (title) => `${title} - ${appName}`,
resolve: (name) => resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob('./Pages/**/*.vue')),
setup({ el, app, props, plugin }) {
return createApp({ render: () => h(app, props) })
.use(plugin)
.use(ZiggyVue, Ziggy)
.use(PrimeVue)
/*added by me*/ .component('InputMask', InputMask)
.mount(el);
},
});
InertiaProgress.init({ color: '#4B5563' });
To add the fullscreen button to my leaflet map into nuxt i have installed leaflet.fullscreen package and i have edited my plugin leaflet.js like so:
import Vue from "vue";
import { LMap, LTileLayer, LMarker, LPolyline } from "vue2-leaflet";
require("leaflet-routing-machine");
require("lrm-graphhopper");
require("leaflet.fullscreen");
So i can use it in my main template:
<template>
<div>
<section class="search__page">
<div id="map-wrap" class="map__wrapper"></div>
</section>
</div>
</template>
<script>
import Tmap from "#/utils/TripMap.js";
export default {
mounted() {
this.initTmap();
},
data() {
return {
mainMap: null,
},
methods: {
initTmap() {
this.mainMap = new Tmap();
this.mainMap.load();
}
}
}
</script>
My class looks like that :
export default class Tmap {
constructor() {
this.map = null;
}
load) {
this.map = L.map("map-wrap", {
fullscreenControl: true,
fullscreenControlOptions: {
position: "topleft"
}).setView([46.7227062, 2.5046503], 6);
L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png", {
maxZoom: 18,
attribution: '© OpenStreetMap, ©TRIP'
}).addTo(this.map);
}
addMarkerOnClick() {
this.map.addEventListener("click", ev => {
L.marker(ev.latlng).addTo(this.map);
});
}
getBounds() {
return this.map.getBounds();
}
}
So in my main component i don't know how to import the css associated to this fullscreen plugin. I tried :
<style>
#import "~/node_modules/leaflet.fullscreen/Control.FullScreen.css";
</style>
That works but it's obviously not the good way to do that. Any idea how to that properly ?
From a quick web research i would say you should be able to access the styles like this:
#import "~leaflet/dist/leaflet.css";
When you register a global style in your nuxt.config.js the app will load it just once. I assume your build is taking more time than normal due to the node_modules path.
// nuxt.config.js
css: ['~/assets/styles/global.css'],
You could also give the nuxt resource loader a try.
I'm using create-react-app for a multi-language project.
I want to use some library like "cssJanus" or "rtlcss" to convert the Sass generated CSS file into a separate file and then use that newly generated file when I switch to another language.
Here's how my index.js looks like ...
import React from "react";
import ReactDOM from "react-dom";
import * as serviceWorker from "./serviceWorker";
import { BrowserRouter as Router } from "react-router-dom";
import { Provider } from "react-redux";
import App from "./App";
import { configureStore } from "./store/configureStore";
const store = configureStore();
ReactDOM.render(
<Provider store={store}>
<Router>
<App />
</Router>
</Provider>,
document.getElementById("root")
);
serviceWorker.unregister();
And here's how my "App.js" looks like ...
import React, { Component } from "react";
import "./App.scss";
import { Route, Switch } from "react-router-dom";
import SignIn from "./features/signin/SignIn";
class App extends Component {
render() {
return (
<>
<Switch>
<Route path="/" exact component={SignIn} />
</Switch>
</>
);
}
}
export default App;
As you can see I'm using "./App.scss" file that simply have a bunch of #import statements to another ".scss" files in the "./src/css/" directory ...
/* autoprefixer grid: on */
#import "css/reset";
#import "css/variables";
#import "css/global";
I need your advice on how to do that. How to convert the generated CSS from App.scss to RTL into their own .css file and switch between them and the original generated CSS based on a change in the global state.
I searched a lot for something like this but with no luck.
Or if you have a better approach I'm all ears.
Here is a simple solution that requires ejecting and adding a lightweight webpack-rtl-plugin.
After running
npx create-react-app react-rtl
cd react-rtl
yarn eject
yarn add -D webpack-rtl-plugin #babel/plugin-transform-react-jsx-source
Go to config/webpack.config.js and make some tweaks:
// import the plugin
const WebpackRTLPlugin = require('webpack-rtl-plugin')
// ...
module: { ... }
plugins: [
// ...,
// use the plugin
new WebpackRTLPlugin({ diffOnly: true })
].filter(Boolean),
// ...
On this stage, if you run yarn build and look up build/static/css folder, you should hopefully see additional .rtl.css file that contains your rtl styles.
Then we need to tell webpack to use MiniCssExtractPlugin.loader for development as well so it will serve styles through link tags instead of inline styles:
// common function to get style loaders
const getStyleLoaders = (cssOptions, preProcessor) => {
const loaders = [
isEnvDevelopment && { loader: MiniCssExtractPlugin.loader }, // <-- use this
// isEnvDevelopment && require.resolve('style-loader'), <-- instead of this
and don't forget the plugin, lol:
module: { ... }
plugins: [
// ...,
// isEnvProduction && <-- comment this out
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: 'static/css/[name].[contenthash:8].css',
chunkFilename: 'static/css/[name].[contenthash:8].chunk.css',
}),
// ...
].filter(Boolean),
And from here you can finally grab your default stylesheet href and use to insert rtl styles. Here's how you could implement it:
class RtlCssBundleService {
constructor() {
this.rtlApplied = false
this.rtlStyles = [];
this.ltrStyles = Array.from(
document.querySelectorAll('link[rel="stylesheet"]')
)
}
insert = () => {
if (this.rtlApplied) { return }
this.rtlApplied = true
if (this.rtlStyles.length) {
return this.rtlStyles.forEach(style => {
document.body.appendChild(style)
})
}
this.rtlStyles = this.ltrStyles.map(styleSheet => {
const link = document.createElement("link")
link.href = styleSheet.href.replace(/\.css$/, '.rtl.css')
link.rel = "stylesheet"
document.body.appendChild(link)
return link
})
}
detach = () => {
this.rtlApplied = false
this.rtlStyles.forEach(style => {
document.body.removeChild(style)
})
}
toggle = () => {
return this.rtlApplied
? this.detach()
: this.insert()
}
}
const rtlStyles = new RtlCssBundleService()
export default rtlStyles
Then use this from any of your components.
So anyway, I'm sure I've missed something and maybe that is a terrible approach, but it seems to work and here is the demo
If you use flexbox and css grid they have RTL support built in. Then use CSS Logical Properties for margin, padding, border, etc. If that is not enough, then you can use [dir="rtl"] .your-class as a fallback.
Now you don't have two separate css files to maintain.
Here is a cross browser margin-right example.
-webkit-margin-end: 25px;
margin-inline-end: 25px;
#supports (not (-webkit-margin-end: 0)) and (not (margin-inline-end: 0)) {
margin-right: 25px;
}
You could wrap that up into a mixin for easier use across your app.
Looking around there is a library called react-with-direction from airbnb that provides a DirectionProvider - component you could wrap your components in based on the language. Hope that helps.
My project has two main parts. One for public web pages and the other for admin control panel. Each of them has separate CSS and javascript files for their template.
If I define all CSS and js files in index.html, all files load in the first meet of the web page, and also maybe have a conflict between CSS classes.
How can I handle this problem?
app.component:
<router-outlet></router-outlet>
app-routing.module:
import { NgModule } from "#angular/core";
import { Routes, RouterModule } from "#angular/router";
import { FirstComponent } from './first/first.component';
const appRoutes: Routes = [
{ path: 'first', component: FirstComponent },
{
path: 'controlpanel',
loadChildren: 'app/control-panel/control-panel.module#ControlPanelModule'
},
{
path: 'publicpanel',
loadChildren: 'app/public-panel/public-panel.module#PublicPanelModule'
}
];
each module has its submodules. Can I separate their styles?
Use sass and create a class flag for public and admin components
like this
theme/_public.scss
.public{
label {
color:red;
}
}
theme/_admin.scss
.admin {
label {
color:green;
}
}
and this in main style.scc
#import "theme/_public.scss";
#import "theme/_admin.scss";
this is much better for app performance you will have one style file with public and admin pages style
stackblitz example
I found the solution. We can disable or enable css files in component.
document.styleSheets[2].disabled = false;
or
document.styleSheets[2].disabled = true;
that's it.
I have a minimal React component which consists of two files: button.jsx and button.less. The styles are imported and the class names are appended with a hash to make all styles local to the component.
This is great, but i'd like to have all component code in one file. Is it possible to inline the styles in jsx file without losing css modularity?
Current Code
button.jsx
import React from 'react';
import styles from './button.less'
export default class Button extends React.Component {
render() {
return <button className={styles.primary}>{this.props.text}</button>;
}
}
button.less
#import '~semantic-ui/src/definitions/elements/button.less';
.common {
composes: ui button;
}
.primary {
composes: common primary;
}
webpack.config.js (relevant bits)
module: {
loaders: [
{
test: /\.jsx$/,
loader: 'babel'
},
{
test: /\.less$/,
loader: "style!css?modules&importLoaders=1!less"
}
]
},
What i'd like to write instead
button.jsx
<style lang="less" modules>
#import '~semantic-ui/src/definitions/elements/button.less';
.common {
composes: ui button;
}
.primary {
composes: common primary;
}
</style>
import React from 'react';
export default class Button extends React.Component {
render() {
return <button className={styles.primary}>{this.props.text}</button>;
}
}
Inspired by vue.js and vue-loader.
I believe this is a duplicate of this unanswered question:
Using css-loader inline with Webpack + React
I wrote a Webpack loader for this very purpose:
https://github.com/chrisdavies/stylextract-loader
It allows you to write a single style tag per JSX file and it supports webpack CSS modules, too, if you want.
At build time, it extracts the rules from your style tag and moves them out to an external CSS file.
I should note that because it simply extracts your rules out to an external CSS file, it plays nice with SASS, autoprefixer, etc
You can use callback-loader for this. This is actualy a workaround, but it do the trick. Just implement a callback which will extract your css-code and replace it with appropriate import. For example:
webpack.config.js
var fs = require('fs');
var cssIndex = 0;
// Do not forget to create and clean temporary folder "cssTemp" before
var webpackConfig = {
...
resolve: {
alias: {
cssTemp: path.resolve('./cssTemp')
}
},
module: {
loaders: [
{ test: /\.jsx$/, loader: "callback!babel" }
]
},
callbackLoader: {
cssCallback: function(code) {
var filename = cssIndex + '.less';
cssIndex++;
// Save the css code from the callback argument
fs.writeFileSync('./cssTemp/' + filename, code);
// Return the import statement which will replace the callback statement
return 'import styles from "cssTemp/' + filename + '";';
}
}
...
};
button.jsx
import React from 'react';
cssCallback(`
#import '~semantic-ui/src/definitions/elements/button.less';
.common {
composes: ui button;
}
.primary {
composes: common primary;
}
`);
export default class Button extends React.Component {
render() {
return <button className={styles.primary}>{this.props.text}</button>;
}
}