How to integrate local fonts into an Electron React Boilerplate App? - css

What does not work
I am trying to add some custom local fonts into my Electron React App, but i would like to do it without installing the fonts on my computer.
Current partial solution
The only way, which works for me, it is to install the fonts on my computer, but i would like to find a better solution.
I placed my fonts files into:
assets/fonts/
And i tried to use it in my scss file located in:
src/renderer/scss/commons/_fonts.scss
In this way:
#font-face {
font-family: 'Bariol Regular';
font-style: normal;
font-weight: normal;
src: local('Bariol Regular'),
url('/assets/fonts/Bariol-Regular.ttf') format('ttf');
}
These are my current Electron versions
"electron": "^15.1.0",
"electron-builder": "^22.11.7",
"electron-devtools-installer": "^3.2.0",
"electron-notarize": "^1.1.1",
"electron-rebuild": "^3.2.3",
How html has been loaded into electron:
new HtmlWebpackPlugin({
filename: path.join('index.html'),
template: path.join(webpackPaths.srcRendererPath, 'index.ejs'),
minify: {
collapseWhitespace: true,
removeAttributeQuotes: true,
removeComments: true,
},
isBrowser: false,
env: process.env.NODE_ENV,
isDevelopment: process.env.NODE_ENV !== 'production',
nodeModules: webpackPaths.appNodeModulesPath,
}),
The React App component has been mounted into the index.ejs file on the
<div id="root"></div>
And the scss file which contains the fonts rule, has been imported into the App.tsx file.
import './App.global.scss';
I would be grateful if someone could help me.
And i hope this could help someone else.
Thank you!

It's hard to tell how similar our setup is, but hopefully this helps someone.
My issue was putting the fonts in my public folder when they're supposed to be under src.
I made a fonts folder under src, then I declared the font in a css file. e.g:
/* src/index.css */
#font-face {
font-family: 'KleeOne';
src: url('./fonts/KleeOne-SemiBold.ttf');
}
After that, I imported the css in my index.js and it worked:
/* src/index.js */
import './index.css';

Related

Custom font not loading in react direflow application

I have created a javascript direflow application. I am trying to load a local font but haven't been able to.
Below are the details and code snippets I have applied.
Folder Structure
font.css
#font-face {
font-family: 'MyLocalFont';
src: local('MyLocalFont'),
url('./fonts/MyLocalFont.woff') format('woff'),
url('./fonts/MyLocalFont.woff2') format('woff2');
}
direflow-components/testing-component/index.js
plugins: [
{
name: 'font-loader',
options: {
custom: {
families: ['MyLocalFont'],
urls: ['/fonts.css']
},
},
},
],
App.css
.header-title {
font-size: 34px;
color: #5781C2;
font-family: 'MyLocalFont';
}
The font files doesn't load. Please help.
Note: Built a react app using create-react-app there with #font-face changes the fonts load. Something with direflow is not working.
I resolved the issue seems like the plugin font-loader is not required. I removed it from direflow-components/testing-component/index.js.
Another change I made is removed the single quotes from the font-family.
App.css
.header-title {
font-family: MyLocalFont;
}

Custom TTF fonts loading slowly in React app

I'm trying to include a custom font in my React app (made with create-react-app). It seems to be somewhat working but only after 2-3 second after loading the page. Until then, the text appears to use the browser's default font (like Times New Roman), and then swaps to the custom font after a few seconds. Can someone please explain to me why this is happening and what I need to do to fix this?
I'm importing the font into my top-level App.js file like so:
import './fonts/tarrgetital.ttf';
import './App.scss';
And have it declared in my App.scss file like so:
#font-face {
font-family: 'tarrgetital';
src: local('tarrgetital'), url(./fonts/tarrgetital.ttf) format('truetype');
}
h2 {
font-family: tarrgetital;
}
The delay in loading the web fonts is an expected behaviour issue and it's happening because the browser load the fonts when it detects a DOM element with a CSS selector that matches the font-face rule and that happens when then HTML file and all the CSS files have been downloaded on the client. It's a lazy loading mechanism. There are some solutions to improve this behavior:
Use optimized web font file:
For better performance, you can swap your TTF font file in the
font-face with the woff and woff2 file formats. these formats are
compressed in gzip thus reducing the file size and initial
downloading time on the client. If those formats are not available
you can use one of many online tools to convert the font file (google
TTF to woff2).
Webpack Preload:
In webpack 4.6.0+ you can preload modules. this uses
the preload hint in HTML link tags (<link rel="preload">). it will tell the browser to preload the resource before downloading the rest of the resources. To use this option replace import './fonts/tarrgetital.ttf'; with import(/* webpackPreload: true */ './fonts/tarrgetital.ttf');
More on webpack preload here: https://webpack.js.org/guides/code-splitting/#prefetchingpreloading-modules and more info on HTML preload hint here: https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content
One alternative is to use webfontloader. It was co-developed by Google and Typekit.
npm i webfontloader
In your App.js file add this one. Note: You still have to maintain your font face declarations at your css file.
import WebFont from 'webfontloader';
WebFont.load({
custom: {
families: ['tarrgetital'],
},
});
I use also font-face on index.css file
#font-face {
font-family: "Avenir";
src: local("Avenir"),
url("assets/fonts/AvenirNextLTPro-Regular.ttf") format("truetype");
font-weight: normal;
font-style: normal;
}
<link rel="stylesheet" href="../src/index.css" />
Then I imported index.css file into index.html, this worked for me.
Use document.fonts.load with useEffect
import React, { useEffect, useState } from 'react';
const MyComponent = () => {
const [loading, setLoading] = useState(true);
useEffect( ()=> {
document.fonts.load("12px Font-Name").then( () => { setLoading(false) } );
}, [])
return (
<React.Fragment>
{ loading
? <div> Loading... </div>
: <main> Rest of Elements </main>
}
</React.Fragment>
);
};
export default MyComponent;

When use subdomain in Flask, how to access static files quoted in css url and js files used require.js?

Flask static settings:
app = Flask(__name__.split('.')[0], static_folder=None)
app.static_url_path = '/static'
app.static_folder = 'static'
app.add_url_rule(app.static_url_path + '/<path:filename>',
endpoint='static',
view_func=app.send_static_file)
CSS
#font-face {
font-family: MuiiconSpread;
font-weight: normal;
font-style: normal;
src: url('../fonts/icons.ttf') format('truetype');
}
JS
require.config({
paths: {
'jquery': '/static/plugins/jquery-3.3.1/jquery.min',
},
});
While access the subdomain such as: a.test.com, the icons.ttf and jquery.min.js are 404 error.
When I add subdomain='a' in add_url_rule for static, everything will be fine. But it just matches a.test.com, while access b.test.com should change the same config to subdomain='b'.
How to fix it?
I faced same issue.
Based on research, I understand that Flask-CORS is the best solution.
But for temporary fix, I have added below code in __init__.py file in the root folder.
#app.after_request
def after_request(response):
if request.endpoint.startswith('static'):
response.headers.add('Access-Control-Allow-Origin', '*')
return response

Font doesn't get loaded through webpack

Hello dear webpack community.
I desperately try to load fonts using the file-loader
I tried both of these rules:
{ test: /\.(woff|eot|svg|otf|ttf)$/i, loader: `file-loader`, options: {name:'fonts/[name].[ext]'}},
{ test: /\.(woff|eot|svg|otf|ttf)$/i, loader: `file-loader?name=fonts/[name].[ext]`},
however, unfortunately, the fonts don't get pulled when asked for them in the #font-face rule:
#font-face {
font-family: 'Example';
font-style: normal;
font-weight: 400;
src: url('../fonts/Example.ttf') format('truetype');
}
This is how my project structure looks like:
This is the Webpack output:
While fonts.less is loaded, I don't see any font getting loaded through the definition of src().
Thank you a lot for any hint in advance!
See the full config file here: https://gist.github.com/MartinMuzatko/2873b52fed204bd6e8aaaa94527e34a9
The problem is that you're using raw-loader to transform the output of the less-loader to JavaScript so that extract-text-webpack-plugin can use it.
{
test: /\.less$/, use: ExtractTextPlugin.extract(
[
{loader:'raw'},
{loader:'less'}
]
),
}
The less-loader simply transforms the Less syntax to regular CSS. The url() won't be touched. The css-loader on the other hand treats them as imports that webpack will resolve. Only then your rules for the fonts will take effect. All you need to do is change your .less rule to use css-loader instead of raw-loader:
{
test: /\.less$/, use: ExtractTextPlugin.extract(
[
{loader:'css'},
{loader:'less'}
]
),
}

Can I bundle sass and css under bower_components with using gulp

I use gulp-compass and gulp-postcss.
I couldn't find best way to locate css files and the dependencies files public folder like webroot/css with gulp. I show partial gulpfile.js bellow.
var postcss = require('gulp-postcss');
var cssnano = require('cssnano');
var atImport = require('postcss-import');
var vendorCssPath =
[
path.join(app_root,'/bower_components/material-design-icons/iconfont/material-icons.css')
];
gulp.task('css', function () {
var processors = [
atImport(),
cssnano()
];
return gulp.src(vendorCssPath)
.pipe(cache('css'))
.pipe(postcss(processors))
.pipe(gulp.dest(path.join(projectDir,'/css')));
});
It works about material-icons.css, but this output doesn't include files which depended on (ex:MaterialIcons-Regular.eot MaterialIcons-Regular.svg MaterialIcons-Regular.woff MaterialIcons-Regular.ijmap MaterialIcons-Regular.ttf MaterialIcons-Regular.woff2).
I want these assets locate public folder with gulp.Though it is enough, better these files and compiled css file with gulp-compass are bundled to css file if it is possible.
Do you have any idea?
So the thing is that you have to copy fonts from bower dependencies to your build folder (or to your src folder if you use some other task for managing fonts). The best way is to make gulp task which will copy fonts (in case you update dependencies you can run font task and it will copy updated files).
Then you can use SASS for adding fonts:
// FONTS
// ---------------------------------------------------
#mixin font-face($fontFamily, $src, $fontName){
#font-face {
font-family: $fontFamily;
src: url("#{$src}#{$fontName}.eot");
src: url("#{$src}#{$fontName}.eot?#iefix") format("embedded-opentype"),
url("#{$src}#{$fontName}.woff") format("woff"),
url("#{$src}#{$fontName}.ttf") format("truetype"),
url("#{$src}#{$fontName}.svg##{$fontFamily}") format("svg");
}
}
#include font-face('Material Icons', '/assets/build/fonts/MaterialIcons/', 'MaterialIcons-Regular');
And CSS you can include in your main SCSS file, for example in main.scss:
#import './bower_components/material-design-icons/iconfont/material-icons.css';
You can read more here http://google.github.io/material-design-icons/

Resources