where to place next/font inside nx workspace - next.js

i have a NX workspace with nextjs and a few libraries. im using mui as the component library. im also using #next/font to load a google font.
I have created a library for the mui theme, i which i export a singel theme i want to use across entire application. there is no problem with the theme except for the font part. i did it exactly like this, https://github.com/mui/material-ui/blob/master/examples/nextjs-with-typescript/src/theme.ts this example comes from the miu repo. i get the following error:
Font loaders cannot be used from within node_modules.
Location: ..\..\libs\shared\ui\src\lib\shared-ui.tsx
this is my project.json for the nx workspace
{
"name": "shared-ui",
"$schema": "../../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "libs/shared/ui/src",
**"projectType": "library",**
"tags": [],
"targets": {
"lint": {
"executor": "#nrwl/linter:eslint",
"outputs": ["{options.outputFile}"],
"options": {
"lintFilePatterns": ["libs/shared/ui/**/*.{ts,tsx,js,jsx}"]
}
},
"test": {
"executor": "#nrwl/jest:jest",
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
"options": {
"jestConfig": "libs/shared/ui/jest.config.ts",
"passWithNoTests": true
}
}
}
}
as u can see it is a lib.
how can i use the next/font with mui inside a NX workspace?

I got the same error with similar setup (themes coming from a shared ui Nx lib). I worked around it by passing in the font as a parameter under /apps to the theme provider component under /libs. I guess Next needs the font loader to be called in the app itself to do its magic.
import { Roboto } from '#next/font/google';
import { CustomThemeProvider } from '#shared-ui';
...
const roboto = Roboto({...});
...
<CustomThemeProvider fontFamily={roboto.style.fontFamily}>{children}</CustomThemeProvider>

Related

How to develop/debug two apps with shared components using vue3 and vite?

I'm building a couple of apps with vue3 and vite, using some shared components. The production build process works OK but I'm having a problem with dev/debug. The Vite docs (for multi-page apps) says
"During dev, simply navigate or link to /nested/ - it works as
expected, just like for a normal static file server."
but I don't know what this means - how do I link to a sub folder? I have added /src/app1 to url in launch.json, but it has no effect. I have also tried using cd src\app1 in the terminal before running npm run dev
"version": "0.2.0",
"configurations": [
{
"type": "firefox",
"request": "launch",
"name": "vuejs: firefox -width 300 -height 600 -P default",
"url": "http://localhost:5173/src/app1",
"webRoot": "${workspaceFolder}",
"pathMappings": [
{
"url": "file:///C:",
"path": "c:"
}
]
}
]
(This launch.json works well with a simple single-page app).
What happens with trying to debug one of the apps is that the project launches but with an empty index.html (i.e. a blank screen with no errors). I'm pretty sure the basic project structure is OK because (as I said) the build process works; I get two separate outputs of html+css+js both of which work as expected, with the correct shared components.
Also, if I tell the Vite server to automatically open the page (as I have done in my vite.config.js below) the page opens correctly - although without a debugger attached of course. So I guess that the settings in launch.json are incorrect.
The project structure is:
-src
-app1
-app.vue
-index.html
-main.js
-app2
-app.vue
-index.html
-main.js
-assets
...
-shared
-components
-shared.vue
If I have just one index.html, moved up a level, I can debug each app but only by editing it every time to point to a different main.js and to change the title, which seems a laborious way of approaching the task.
Below is my vite config. The extra lines in alias were added as an attempt to solve the problem but they are probably incorrect (or unneccesary)
import { fileURLToPath, URL } from 'node:url'
import { resolve } from 'path'
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
server: {
base: '/src/app1',
open: '/src/app1/index.html',
},
resolve: {
alias: {
vue: 'vue/dist/vue.esm-bundler.js',
'#': fileURLToPath(new URL('./src', import.meta.url)),
app1: fileURLToPath(new URL('./src/app1', import.meta.url)),
app2: fileURLToPath(new URL('./src/app2', import.meta.url)),
// shared: fileURLToPath(new URL('./src/shared/components', import.meta.url)),
}
},
build: {
rollupOptions: {
input: {
app1: resolve(__dirname, './src/app1/index.html'),
app2: resolve(__dirname, './src/app2/index.html'),
},
},
},
})
I've made things more complex than neccesary because I missed the important setting. In vite.config.js, it's important to define root to point to where each index.html is found. So for my structure above, the config file looks like
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
export default defineConfig({
plugins: [vue() ],
root: "src\app1",
resolve: {
alias: {
vue: 'vue/dist/vue.esm-bundler.js',
}
}
})
In the process I've also swapped from Firefox to Chrome for debug (I was getting a lot of irrelevant error messages from Firefox), and my launch.json is now simply
{
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"name": "Launch Chrome against localhost",
"url": "http://localhost:5173",
"webRoot": "${workspaceFolder}",
}
]
}
It doesn't really matter what the file structure looks like, as long as within each file its dependencies are correctly addressed. The only important bit is the root. Simply by changing that from 'app1' to 'app2' will switch both the debug and the build to the correct folders, with the release (built) files being stored in subfolders of 'app1' and 'app2' independently.
It would be easy to extend this to have more than 2 apps each sharing the same common components.

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

Set Global Styles Without Class Hashing in Nuxt

I have numerous Vue SPAs in a monorepo that all share a common set of global styles, each SPA and the styles are their own package.json workspace. I'm trying to replace one of them with Nuxt.
The global styles are .scss files, they import Vue bootstrap and have some custom variables and classes.
As such, I did a fresh install of Nuxt and then ran:
yarn add -D sass sass-loader#10 fibers
I know I can get global styles like so:
//in nuxt.config.js:
css: [resolve(__dirname+'/../common/styles/index.scss')
Really I thought that should/would be it, and I see it does get injected into the page. However, the class names are hashed, so it doesn't apply to my components.
Instead of this (fake css to test if it goes in the page):
.test{
text-align: test;
top: test;
}
I get this:
.olAmdkaWN_JnK1npjbKiI {
text-align: test;
top: test;
}
How can I stop the global styles from being hashed like this, especially when I may be importing components from the other SPAs/common and their classnames aren't being hashed in the HTML? Only the injected global styles are getting hashed like this.
I've tried various attempts at setting the localIdentName such as:
//in nuxt.config.js
build: {
extend(config) {
config.module.rules.push({
test: /\.scss$/,
use: [{
loader: 'css-loader',
options: {
modules: false
/*
or sometimes I'll try something like:
modules:{
localIdentName: '[local]'
}
*/
}
},
{
loader: 'sass-loader'
}
]
})
},
I've also set:
cssModules: {
localIdentName: '[local]'
},
Again in the nuxt.config.js. But nothing works and furthermore I think I must have a conceptual error about how global styles are meant to work, as I feel like I'm fighting the framework rather than working with it.
My nuxt, webpack and sass-loader verisons are as follows:
nuxt#2.15.4
webpack#4.46.0
sass-loader#10.1.1 (It was at 7.1.x but the console suggested upgrading it - didn't make a difference in terms of solving this)
package.json:
"dependencies": {
"core-js": "^3.9.1",
"common": "1.0.0", (local dependency)
"nuxt": "^2.15.3"
},
"devDependencies": {
"fibers": "^5.0.0",
"sass": "^1.32.11",
"sass-loader": "10"
}
Turns out all I needed was this (the key was to put it in loaders within build):
//in nuxt.config.js
build: {
loaders: {
cssModules: {
localIdentName: '[local]'
},
},
}
Please note this only works if you properly install your dependencies and heed build warnings in regards to css-loader and sass-loader. I tried downgrading sass-loader and this didn't work until I put it back at "10" which is what Nuxt expected (threw a warning).

Why does there appear to be non deterministic behavior trying to load a babel plugin in a nextjs project? Next - Babel

I have a nextjs app with redux.
When I try to use the ?? operator in my pages/index, it works as it should.
I then tried to load up a redux store with a bunch of reducers. When I hit the ?? in a reducer file, I get this error:
Support for the experimental syntax 'optionalChaining' isn't currently enabled (71:32):
I also get the error in any other file: component, actions and reducers. It is only directly in the pages/* that the plugin is working properly.
My app is using next#9.1.1 and redux#4.0.4. Here is my .babelrc file:
"env": {
"development": {
"presets": ["next/babel"],
"plugins": [
"#babel/plugin-proposal-optional-chaining",
"#babel/plugin-proposal-nullish-coalescing-operator",
[
"styled-components",
{ "ssr": true, "displayName": true, "preprocess": false }
]
]
}
}
}
Is there something that would override my babel config for certain files? If so, what am I missing? What else should I look at?

How to add global style to angular 6/7 library

I was trying to add global styles in the same way like in angular app, but it totally does not work.
My libraries' name is example-lib, so I added styles.css to /projects/example-lib/. I added styles in main angular.json file:
...
"example-lib": {
"root": "projects/example-lib",
"sourceRoot": "projects/example-lib/src",
"projectType": "library",
"prefix": "ngx",
"architect": {
"build": {
"builder": "#angular-devkit/build-ng-packagr:build",
"options": {
"tsConfig": "projects/example-lib/tsconfig.lib.json",
"project": "projects/example-lib/ng-package.json",
"styles": [
"projects/example-lib/styles.css" <!-- HERE
],
},
...
But when I tried build library using command:
ng build example-lib
I got error:
Schema validation failed with the following errors:
Data path "" should NOT have additional properties(styles)
I guess that is the other way to add global styles in separate library. Anyone can help me?
I have a workaround for this. Just create the root component of your library without view encapsulation and all its styles will be then global.
my-library.component.ts
import { Component, OnInit, ViewEncapsulation } from '#angular/core';
#Component({
selector: 'lib-my-library',
templateUrl: './my-library.component.html',
styleUrls: ['./my-library.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class MyLibraryComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
my-library.component.html
<!-- html content -->
my-library.component.scss
#import './styles/core.scss';
Now your my-library.component.scss and core.scss are global
styles/core.scss
body {
background: #333;
}
core.scss is optional, I just like to keep the root files clean.
Update: In case you want your mixins and variables too, then follow this answer.
As #codeepic already pointed out, there is currently a standard solution.
In ng-package.json add
"assets": ["./styles/**/*.css"]
The provided paths should be the paths to your files. At the same time, they will be the paths inside your /dist folder.
On build, the files will be copied to /dist. Users of your library will be able to add them to their global styles as follows.
/* styles.css */
#import url('node_modules/<your-library-name>/styles/<file-name>');
This way you can copy any type of files.
P.S. When used with CSS, do not forget that you can create an index.css file that can be imported just like node_modules/<your-library-name>/styles.
From Compiling css in new Angular 6 libraries:
install some devDependencies in our library in order to bundle the css:
ng-packagr
scss-bundle
ts-node
Create css-bundle.ts:
import { relative } from 'path';
import { Bundler } from 'scss-bundle';
import { writeFile } from 'fs-extra';
/** Bundles all SCSS files into a single file */
async function bundleScss() {
const { found, bundledContent, imports } = await new Bundler()
.Bundle('./src/_theme.scss', ['./src/**/*.scss']);
if (imports) {
const cwd = process.cwd();
const filesNotFound = imports
.filter(x => !x.found)
.map(x => relative(cwd, x.filePath));
if (filesNotFound.length) {
console.error(`SCSS imports failed \n\n${filesNotFound.join('\n - ')}\n`);
throw new Error('One or more SCSS imports failed');
}
}
if (found) {
await writeFile('./dist/_theme.scss', bundledContent);
}
}
bundleScss();
Add _theme.scss inside the /src directory of the library that actually contains and imports all the css that we want to bundle.
Add postbuild npm script to run the css-bundle.ts
Include it in the styles tag in your Application in the angular.json
From this issue solution
Install cpx and scss-bundle as Dev dependencies to your package.json. Then add the following entries in your package.json "scripts" property:
"scripts": {
...
"build-mylib": "ng build mylib && npm run build-mylib-styles && npm run cp-mylib-assets",
"build-mylib-styles": "cpx \"./projects/mylib/src/lib/style/**/*\" \"./dist/mylib/style\" && scss-bundle -e ./projects/mylib/src/lib/style/_style.scss -d ./dist/mylib/style/_styles.scss",
"cp-mylib-assets": "cpx \"./src/assets/**/*\" \"./dist/mylib/assets\"",
...
}
Replace "mylib" with your real library name and then just run in your terminal build-mylib. That would compile your scss assets to your dist folder.
You use this global styles in your actual Angular project just import them in your angular.json file within your project settings:
"styles": [
"src/styles.scss",
"dist/my-shiny-library/_theme.scss"
],
(use dist if your project is in the same workspace, or node_moduled if its an imported library)
1- be sure you are putting your styles inside the library
example:
projects/your-lib-name/assets/styles.css
2- then in your ng-package.json (in the lib for sure) put the assets rule
{
"$schema": ... ,
"dest": ... ,
> "assets": [
> "./assets/*"
> ],
"lib": ...
}
3-
in your application, you can use this asset
"styles": [
"../your-lib-name/assets/styles.css"
]
this is a tutorial

Resources