rohanray / next-fonts Goto Github PK
View Code? Open in Web Editor NEWThis project forked from twopluszero/next-images
Import fonts in Next.js (supports woff, woff2, eot, ttf, otf & svg)
This project forked from twopluszero/next-images
Import fonts in Next.js (supports woff, woff2, eot, ttf, otf & svg)
The with-local-fonts example shows a FOIT on initial page load.
Is this something that can be avoided with SSR ?
yarn add next-fonts
yarn add v1.19.1
[1/4] ๐ Resolving packages...
[2/4] ๐ Fetching packages...
[3/4] ๐ Linking dependencies...
warning "next-fonts > [email protected]" has unmet peer dependency "webpack@^2.0.0 || ^3.0.0 || ^4.0.0".
warning "next-fonts > [email protected]" has unmet peer dependency "webpack@^3.0.0 || ^4.0.0".
[4/4] ๐จ Building fresh packages...
success Saved lockfile.
success Saved 2 new dependencies.
info Direct dependencies
โโ [email protected]
info All dependencies
โโ [email protected]
โโ [email protected]
โจ Done in 4.33s.
Hi @rohanray, what do you think about bumping file-loader
and url-loader
to their latest versions? This will bring this package more inline with next-images
. Bumping these deps to their latest versions would require a minimum node version of 10.13, which is the same as the current nextjs version.
the README suggests I do:
const withFonts = require('next-fonts');
module.exports = withFonts({
webpack(config, options) {
return config;
}
});
but my next.config.js
already contains:
const withPlugins = require("next-compose-plugins")
const withImages = require("next-images")
const withSass = require("@zeit/next-sass")
const webpack = require("webpack")
const path = require("path")
module.exports = withPlugins([[withSass], [withImages]], {
webpack(config, options) {
config.resolve.modules.push(path.resolve("./"))
return config
}
})
sorry, but how do I integrate your module into that?
I'm using nextjs with an external dependency which loads fonts via import FontA from '../../fonts/FontA.ttf'
an then uses them in custom css via styled components
...
sadly that breaks nextjs and I'm not able to get this working - using next-fonts
I get an SyntaxError: Invalid or unexpected token
error when trying to access a next page - any idea how to get this setup working with next-fonts
?
Hi. I'm using next-fonts local fonts example to check how it works the plugin with assetPrefix but sadly seems to not work.
Configured an ngrok that points to localhost through public url and configured assetPrefix.
Seems to work for next.js assets but not for fonts
This is the next.config.js file
// next.config.js
const withFonts = require("next-fonts");
module.exports = withFonts({
assetPrefix: "http://f6c62383.ngrok.io/",
webpack(config, options) {
return config;
}
});
Hey,
I use custom css next.js setup to enable 3rd party dependencies to include css. Since 1.1.0
my build is failing with:
Failed to compile.
18:00:37.456 ./node_modules/react-multi-carousel/lib/styles.css
18:00:37.456 ModuleParseError: Module parse failed: Unexpected character '' (1:0)
18:00:37.457 You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
18:00:37.457 (Source code omitted for this binary file)
18:00:37.458 > Build error occurred
18:00:37.459 Error: > Build failed because of webpack errors
18:00:37.459 at build (/zeit/6b3a4e9a/node_modules/next/dist/build/index.js:13:900)
my next.conf.js:
const withPlugins = require('next-compose-plugins');
const withOptimizedImages = require('next-optimized-images');
const withFonts = require('next-fonts');
const withCSS = require('@zeit/next-css');
const webpack = require('webpack');
const FilterWarningsPlugin = require('webpack-filter-warnings-plugin');
const nextConfig = {
env: {
GOOGLE_API_KEY: 'SOME_KEY',
REACT_APP_GOOGLE_MAP_API_KEY:
'SOME_OTHER_KEY',
},
webpack: (config, { isServer }) => {
if (isServer) {
const antStyles = /antd\/.*?\/style\/css.*?/;
const origExternals = [...config.externals];
config.externals = [
(context, request, callback) => {
if (request.match(antStyles)) return callback();
if (typeof origExternals[0] === 'function') {
origExternals[0](context, request, callback);
} else {
callback();
}
},
...(typeof origExternals[0] === 'function' ? [] : origExternals),
];
config.module.rules.unshift({
test: antStyles,
use: 'null-loader',
});
}
// // HOTFIX: https://github.com/webpack-contrib/mini-css-extract-plugin/issues/250
config.plugins.push(
new FilterWarningsPlugin({
exclude: /mini-css-extract-plugin[^]*Conflicting order between:/,
})
);
config.resolve.modules.push(__dirname);
config.plugins.push(new webpack.IgnorePlugin(/(.*)(test|spec)\.(ts|js|tsx|jsx)$/));
return config;
},
};
module.exports = withPlugins(
[
[
withOptimizedImages,
{
mozjpeg: {
quality: 90,
},
webp: {
preset: 'default',
quality: 90,
},
},
],
withFonts,
withCSS,
],
nextConfig
);
If I downgrade to 1.0.3, then everything is fine.
Hello,
I would love to see how to use this package. I want to use it in my .scss file but no idea how to get it work.
I added the package but it does not work as soon the project is deployed via now.
I dropped my .otf|woff files inside of the /static/fonts/my-font-files. Which path do I use in my scss file?
Thanks
Can you please provide a minimal example in the repo?
This plugin is not working with the current version of Nextjs (9).
Not able to add font face with SCSS
Font files are not likely to be changed, can we add enableHash
option which is enabled by default?
Line 30 in 362f314
hi, thanks for creating this package!
i was wondering if it the fonts are supposed to be cached, and if it was possible to set the headers manually?
i checked out the https://github.com/rohanray/next-fonts-example repo, and didn't see any caching headers set on the font.
curl http://localhost:3000/fonts/Montserrat-ExtraLight.ttf -I
HTTP/1.1 200 OK
Accept-Ranges: bytes
Cache-Control: public, max-age=0
Last-Modified: Tue, 07 Apr 2020 06:29:21 GMT
ETag: W/"3b1d0-17153543a99"
Content-Type: font/ttf
Vary: Accept-Encoding
Content-Encoding: gzip
Date: Tue, 07 Apr 2020 16:07:58 GMT
Connection: keep-alive
Transfer-Encoding: chunked
is caching handled by next or this application?
as a workaround (since i'm running nextjs behind a custom express server), i'm basically doing this:
server.get('/fonts/*', function (req, res, next) {
res.set('Cache-Control', 'public, max-age=31557600')
next()
}
to set the cache control headers manually. however, this doesn't help me if i ever decide to break away from express and go serverless.
Hi,
After upgrade from 1.2 to 1.3 i get this Error. Is it possible that someone explain it? With 1.2 everything works fine
error - ./fonts/fira-sans/fira-sans-v10-latin-italic.woff2 1:4 Module parse failed: Unexpected character '' (1:4) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders (Source code omitted for this binary file) wait - compiling...
best Peter
Hey,
i found that after updating next-fonts
to anything >0.10 it breaks my SVG icon loading with next-optimized-images
. All icons are processed before next-optimized-images
can handle them, which leads to compile-time errors with the sprite loader:
Module build failed (from ./node_modules/svg-sprite-loader/lib/loader.js):
InvalidSvg: svg-sprite-loader exception.
module.exports = "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZ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2MTU0IEM1LjIzMDc2OTIzLDkuMDA3OTYxNTQgNS43NjY4NDYxNSw3LjcxMzczMDc3IDYuNzQwMzA3NjksNi43NDAzMDc2OSBDNy43MTM3MzA3Nyw1Ljc2Njg4NDYyIDkuMDA3OTYxNTQsNS4yMzA3NjkyMyAxMC4zODQ2MTU0LDUuMjMwNzY5MjMgQzExLjc2MTI2OTIsNS4yMzA3NjkyMyAxMy4wNTU1LDUuNzY2ODg0NjIgMTQuMDI4OTIzMSw2Ljc0MDMwNzY5IEMxNS4wMDIzNDYyLDcuNzEzNzMwNzcgMTUuNTM4NDYxNSw5LjAwNzk2MTU0IDE1LjUzODQ2MTUsMTAuMzg0NjE1NCBDMTUuNTM4NDYxNSwxMS43NjEyNjkyIDE1LjAwMjM0NjIsMTMuMDU1NSAxNC4wMjg5MjMxLDE0LjAyODkyMzEgQzEzLjA1NTUsMTUuMDAyMzg0NiAxMS43NjEyNjkyLDE1LjUzODQ2MTUgMTAuMzg0NjE1NCwxNS41Mzg0NjE1IEM5LjAwNzk2MTU0LDE1LjUzODQ2MTUgNy43MTM3MzA3NywxNS4wMDIzODQ2IDYuNzQwMzA3NjksMTQuMDI4OTIzMSBDNS43NjY4NDYxNSwxMy4wNTU1IDUuMjMwNzY5MjMsMTEuNzYxMjY5MiA1LjIzMDc2OTIzLDEwLjM4NDYxNTQgWiIgaWQ9IkltcG9ydGVkLUxheWVycyIgZmlsbD0iIzAwMDAwMCI+PC9wYXRoPgogICAgPC9nPgo8L3N2Zz4="
at Object.loader (/xyz/node_modules/svg-sprite-loader/lib/loader.js:29:11)
@ ./components/header/searchBox/index.js 5:0-38 6:24-27
@ ./components/header/index.js
@ ./pages/_app.js
@ multi ./pages/_app.js
It would be nice if we could have SVG font support in next-fonts
as an opt-in.
Best regards and thanks for your work!
Conversation was locked so I'm opening an new issue to discuss deprecation of this plugin. No one wants to see their work deprecated but it can also be a sign of good aging and useful shelf-life. Given the discussion in #34 and the note in the readme I learned this package is no longer needed. But what's not clear is at which version fo Next does is this plug-in no longer needed. Without knowing which version of NextJS this plug-in is no longer needed hundreds of individuals will be forced to do the same research to determine which is a waste of human time if it can be documented.
Personally I'm using an older version of NextJS without an upgrade path (yet) and I think I need this plug-in would be super helpful versus hacks like this. So does anyone know at what version of Next should this plugin be deprecated if at all?
๐ @rohanray WDYT of changing the API of the plugin the following way?
// next.config.js
module.exports = require("next-compose-plugins")([
require("@next/bundle-analyzer")({ enabled: true }),
require("@zeit/next-source-maps")(),
- [require("next-fonts"), { assetPrefix: 'https://example.com', enableSvg: true }],
+ require("next-fonts")({ prefix: 'https://example.com', enableSvg: true }),
])
This request is similar to martpie/next-transpile-modules#52
I'd like to avoid pollution of the config object with plugin-specific options like enableSvg
and also customize prefix
for fonts only.
Line 12 in cf7165c
โ
const assetPrefix = options.prefix !== undefined ? options.prefix : nextConfig.assetPrefix || '';
I'm trying to load in some Google Fonts in ttf format and they don't seem to want to load. I'm using next-fonts as well as SCSS for styling. The fonts are under in /static/fonts/ but I can't figure out what I'm doing wrong. Any help would be appreciated!
I'm loading the plugins like this:
const withSass = require('@zeit/next-sass');
const withFonts = require('next-fonts');
const compose = require('next-compose');
module.exports = compose([[withFonts],[withSass]]);
And my SCSS imports are as such:
@font-face {
font-family: 'Ovo';
font-weight: 400;
src: url('/static/fonts/Ovo-Regular.ttf') format('ttf');
}
@font-face {
font-family: 'Muli';
font-weight: 400;
src: url('/static/fonts/Muli.ttf') format('ttf');
}
@font-face {
font-family: 'Muli';
font-weight: 600;
src: url('/static/fonts/Muli-SemiBold.ttf') format('ttf');
}
please add exemples how use this on application develop
like exemple
next.config.js
const path = require("path");
const withSass = require("@zeit/next-sass");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const withFonts = require("next-fonts");
module.exports = withFonts({
assetPrefix: "https://example.com",
webpack(config, options) {
return config;
}
});
const nextConfig = withSass({
webpack(config, options) {
config.module.rules.push({
test: /\.(raw)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: "raw-loader"
});
config.module.rules.push({
type: "javascript/auto",
test: /\.modernizrrc(\.json)?$/,
use: ["expose-loader?Modernizr", "modernizr-loader", "json-loader"]
});
config.module.rules.push({
test: /\.(png|svg|eot|otf|ttf|woff|woff2)$/,
use: {
loader: "url-loader",
options: {
limit: 100000,
publicPath: "./",
outputPath: "static/",
name: "[name].[ext]"
}
}
});
config.resolve = {
alias: {
modernizr$: path.resolve(__dirname, ".modernizrrc.json")
}
};
if (config.mode === "production") {
if (Array.isArray(config.optimization.minimizer)) {
config.optimization.minimizer.push(new OptimizeCSSAssetsPlugin({}));
}
}
return config;
}
});
nextConfig.exportPathMap = () => {
return {
"/": { page: "/" }
};
};
module.exports = nextConfig;
Iโm currently using styled-components in my project and have setup a _document.js for it but Iโd like to know how to use next-js loader to use it from a npm installed font like https://github.com/KyleAMathews/typefaces
Is it possible?
I'm using Next version 9.3.4 and using next-fonts 1.0.3 and following the instructions to add local .ttf fonts to my app.
The set up is copy and pasted like the styled components example, nothing is that different.
My font files aren't being loaded, I can't find the .ttf file when I use the dev tools, I don't think next is compiling or serving font files?
I checked your example website to https://type-error-idfldxadbv.now.sh/
And this doesn't look like it's working? The dev tools say you're using Pangram font, well it doesn't look like pangram, it looks like the default serif font of the browser.
When Next.js built-in CSS is enabled the fonts are not copied to the build directory properly. Instead of their original content, they contain text like:
module.exports = "/_next/static/chunks/fonts/myfont-8a32f82e77541bcdf4524e59e96b5572.woff";
Perhaps this commit from next-images can be applied here as well:
Line 18 is constrained by enableSvg
so if SVG is disabled, it won't add any loaders. I don't think that the correct intention here. I think you only need to use enableSvg
to add svg or not to the different types of fonts
I added next-fonts
to be able to insert filesystem fonts into my scss file, but the style is not being applied.
Here is a print of the font being loaded: https://i.imgur.com/eiQWPp0.png
Here is my code that applies the style:
h1,
h2,
h3,
h4 {
font-family: "Ubuntu";
}
Here is the font definition code:
@font-face {
font-family: "Ubuntu";
src: url("./fonts/Ubuntu/Ubuntu-Regular.ttf");
}
Here is a print of the font being applied normally: https://i.imgur.com/Z7YsxhH.png
And here a print of the titles (h1, h2...) without the Ubuntu font style: https://i.imgur.com/JBrBk46.png
I had a problem before, and it was because I was adding format
here:
url(". / .....") format ("ttf")
now i remove and add this for test both but none of this works.
The sass code:
@font-face {
font-family: "Ubuntu";
src: url("./fonts/Ubuntu/Ubuntu-Regular.ttf");
}
h1,
h2,
h3,
h4 {
font-family: "Ubuntu";
}
the font original path is changed, ut this apply the new path in a style
tag too:
@font-face {
font-family: "Ubuntu";
src: url(/_next/static/media/Ubuntu-Regular.fa02e22385da5600c6d666df22db9154.ttf);
}
PS: when i add the google font link the style is applied normally
I added .otf font and its working on Google chrome but not on safari.
package.json:
"dependencies": {
"@zeit/next-css": "^1.0.1",
"next": "9.5.2",
"next-fonts": "^1.4.0",
"null-loader": "^4.0.0",
"react": "16.13.1",
"react-dom": "16.13.1",
"styled-components": "^5.1.1"
},
"devDependencies": {
"babel-plugin-styled-components": "1.10.2"
}
_app.js:
import { createGlobalStyle } from "styled-components";
const GlobalStyle = createGlobalStyle`
@font-face {
font-family: 'ProximaNova';
src: url('/static/fonts/ProximaNova-Regular.otf');
src: url('/static/fonts/ProximaNova-Bold.otf');
font-display: auto;
}
p {
font-family: 'ProximaNova';
}
`;
function MyApp({ Component, pageProps }) {
return (
<>
<GlobalStyle />
<Component {...pageProps} />
</>
);
};
export default MyApp
import Head from 'next/head'
import styled from 'styled-components';
export default function Home() {
return (
<div>
<Head>
<title>Create Next App</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main>
<Hello>Hello</Hello>
</main>
</div>
)
}
const Hello = styled.p`
font-family: ProximaNova-Regular;
font-size: 40px;
color: green;
`;
PS: I by mistakenly created this issue in examples admin might. want to delete it from there
next-fonts does not work when you include font-face inside a global scss tag. I.e.
Doing this will not work:-
:global {
@font-face {
font-family: "SomeFont";
src: url("./fonts/SomeFont-Bold.otf") format('opentype');
src: url("./fonts/SomeFont-Bold.woff") format("woff"),
url("./fonts/SomeFont-Bold.ttf") format("truetype"),
url("./fonts/SomeFont-Bold.eot") format("eot"),
url("./fonts/SomeFont-Bold.svg") format("svg");
font-weight: normal;
font-style: normal;
}
}
Please add to documentation
Cheers
Hi @rohanray -- I've been able to successfully import and use locally-packaged fonts (in public/fonts
directory) with @font-face
in a <style jsx global>
tag, in a new NextJS project, without using this package.
Perhaps I'm confused after reading your docs description, which is simply "Import fonts in Next.js (woff, woff2, eot, ttf, otf & svg)", which again seems to work without this plugin. What functionality does this add that's not already provided?
Thank you, and thanks for your work. Just need more detail since I'm fighting bad FOUC in my stub Next app and looking for any way to get the fonts loaded and rendered in the SSG content to avoid it.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.