Configure fonts in webpack - css

I have a slight problem with webpack here; I'm somewhat unable to load fonts.
This is my webpack.config.js
const nodeExternals = require('webpack-node-externals');
const path = require('path');
const devMode = true;
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry:
[
'./src/main.js',
'./scss/main.scss'
],
output: {
filename: "main.min.js",
chunkFilename: '[name].bundle.min.js?bust=[chunkhash]',
path: path.resolve(__dirname, 'static_root'),
publicPath: "/assets/"
},
target: "node",
externals: [nodeExternals()],
plugins: [
new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename: '[id].css',
ignoreOrder: false, // Enable to remove warnings about conflicting order
}),
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.scss$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].css',
outputPath: 'css/'
}
},
{
loader: 'extract-loader'
},
{
loader: 'css-loader'
},
{
loader: 'postcss-loader'
},
{
loader: 'sass-loader'
}
]
},
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: '../',
hmr: process.env.NODE_ENV == 'development',
}
},
],
},
{
test: /\.(woff2?|eot|ttf|otf|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: '[name].[ext]'
}
}
]
}
};
This builds my css although then my local fonts aren't included / aren't rendered.. This also copies my Font to /static_root (which is where the css gets built to).
so I end up with this directory structure:
public/static_root/css/main.css
public/static_root/BebasNeue-Regular.ttf
public/static_root/main.min.js
I thought about just adjusting the path to the font in my scss file unfortunately though this lets the build process fail, since my working dir and the output root aren't the same.
My scss/font-directory is structured like so:
/public/scss/fonts/_fonts.scss
/public/scss/fonts/BebasNeueRegular.ttf
/public/scss/main.scss
So how can I achieve the inclusion of the font or how is this usually done since I found lots of different approaches online, that sadly didn't work out for me.
Any help would be greatly appreciated.
Greetings,
derelektrischemoench

So I found out what was causing the problems. It had to do something with the loader for the fonts (I was using an older one). I tried the whole thing with the url-loader like so:
{
test: /\.(woff2?|eot|ttf|otf|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: '[name].[ext]'
}
}
... which got it going. It was just kinda confusing, since I found a bazillion of tutorials on the web on how to achieve this, of which the most part was deprecated.
Thanks for the responses.

hey #derelektrischemoench, I think the example in Webpack official website is pretty good, you could follow the webpack config and its file structure:
https://webpack.js.org/guides/asset-management/#loading-fonts

Related

How can I load CSS styles using Webpack in React app?

I am having an issue with my React app. I have added Webpack and it is compiling successfully but, at the moment of serving the content, the app shows no styles at all.
This is what I have so far in my webpack.config.js file:
const path = require('path');
const BUILD_DIR = path.resolve(__dirname + '/public/build');
const APP_DIR = path.resolve(__dirname + '/src');
// This is the main configuration object.
// Here, you write different options and tell Webpack what to do
module.exports = {
experiments: {
asyncWebAssembly: true,
topLevelAwait: true,
layers: true // optional, with some bundlers/frameworks it doesn't work without
},
resolve: {
extensions: ['', '.js', '.jsx', '.css']
},
// Path to your entry point. From this file Webpack will begin its work
entry: [APP_DIR + '/index.js', APP_DIR + '/index.css', APP_DIR + '/App.css'],
// Path and filename of your result bundle.
// Webpack will bundle all JavaScript into this file
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
// Default mode for Webpack is production.
// Depending on mode Webpack will apply different things
// on the final bundle. For now, we don't need production's JavaScript
// minifying and other things, so let's set mode to development
mode: 'development',
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
},
{
test: /\.css$/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
modules: true,
},
},
{ loader: 'sass-loader' },
{ loader: 'postcss-loader' }
],
},
]
}
};
Is there anything I am missing to get my css to work? I only have two files, located at /src: App.css and index.css. None of them seem to be loaded and I have no errors in the console.
rules: [
{
test: /\.js|jsx$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.(sass|scss|less|css)$/,
use: [
'style-loader',
'css-loader',
'sass-loader'
]
},
{
test: /\.(png|jpe?g|svg|gif)$/,
loader: 'file-loader'
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
'file-loader',
]
},
{
test: /\.css$/,
use: [
{
loader: 'url-loader',
options: {
limit: false
}
}
]
}
]

How can I grab bunch of scss files and make one css file for all application

I've got webpack.config and don't know what module I need to place in it, cause I found modules, whitch only minimises css or scss files, but not collecting them.
So I have 8-9 scss files, and need one css file, which collects all code from them
var path = require('path');
module.exports = {
entry: {
home: './src/main/js/home/home.js',
products: './src/main/js/products/products.js',
product: './src/main/js/product/product.js',
profile: './src/main/js/profile/profile.js',
topics: './src/main/js/topics/topics.js',
topic: './src/main/js/topic/topic.js',
},
cache: true,
mode: 'development',
output: {
path: __dirname,
filename: './src/main/resources/static/built/[name].bundle.js'
},
module: {
rules: [
{
test: path.join(__dirname, '.'),
exclude: /(node_modules)/,
use: [{
loader: 'babel-loader',
options: {
presets: ["#babel/preset-env", "#babel/preset-react"]
}
}]
}
]
}
};
What module I Should install, and where I need to put code in webpack.config. Please help, I've never worked with webpack!
var path = require('path');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
entry: {
home: './src/main/js/home/home.js',
products: './src/main/js/products/products.js',
product: './src/main/js/product/product.js',
profile: './src/main/js/profile/profile.js',
topics: './src/main/js/topics/topics.js',
topic: './src/main/js/topic/topic.js',
_article: './src/main/resources/static/sass/_article.scss',
_catalog: './src/main/resources/static/sass/_catalog.scss',
_home: './src/main/resources/static/sass/_home.scss',
_header: './src/main/resources/static/sass/_header.scss',
_footer: './src/main/resources/static/sass/_footer.scss',
},
cache: true,
mode: 'development',
output: {
path: __dirname,
filename: './src/main/resources/static/built/[name].bundle.js'
},
module: {
rules: [
{
test: [ /\.scss$/, path.join(__dirname, '.')],
exclude: /(node_modules)/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: ['css-loader', 'sass-loader']
})[{
loader: 'babel-loader',
options: {
presets: ["#babel/preset-env", "#babel/preset-react"]
}
}]
}
]
},
plugins: [
new ExtractTextPlugin("styles.css"),
]
};
That'smy webpack.config
webpack works different than gulp. Gulp is a task runner, which can work with globs and file patterns. Webpack is a bundler, which analyses the dependency tree given your entry points to be able to create your bundles.
In order to work with webpack, and bundle all scss files, they would need to be imported somewhere from your entry point. That is the only way that webpack will know these files exist.
Edit: Correct config.
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: {
home: './src/main/js/home/home.js',
products: './src/main/js/products/products.js',
product: './src/main/js/product/product.js',
profile: './src/main/js/profile/profile.js',
topics: './src/main/js/topics/topics.js',
topic: './src/main/js/topic/topic.js',
_article: './src/main/resources/static/sass/_article.scss',
_catalog: './src/main/resources/static/sass/_catalog.scss',
_home: './src/main/resources/static/sass/_home.scss',
_header: './src/main/resources/static/sass/_header.scss',
_footer: './src/main/resources/static/sass/_footer.scss',
},
cache: true,
mode: 'development',
output: {
path: __dirname,
filename: './src/main/resources/static/built/[name].bundle.js'
},
module: {
rules: [
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader'
]
},
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ["#babel/preset-env", "#babel/preset-react"]
}
}
}
]
},
plugins: [
new MiniCssExtractPlugin()
]
};

webpack 2.7 won't load blueprintjs core css

I'm trying to use blueprintjs and when i'm importing its css. And i think i made something wrong in my webpack config so I see this error
there is my webpack config
const ExtractTextPlugin = require('extract-text-webpack-plugin');
var webpack = require("webpack");
var path = require("path");
module.exports={
entry: './src/index.js',
output:{
path: __dirname + "/public",
filename:'bundle.js',
publicPath: "/public/"
},
devServer: {
inline: true,
contentBase: './public',
port: 3000
},
module:{
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
loader: "babel-loader",
query: {
presets: ['es2015', 'react', 'stage-0'],
}
},
{
test: /\.s(a|c)ss$/,
loader: ExtractTextPlugin.extract({loader: ['css-loader', 'sass-loader', 'style-loader']})
},
{
test: /\.css$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
],
},
{
test: /\.(|gif||svg|woff|woff2|eot|ttf)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader', options: {name: '[name].[ext]'}
}, {
test: /\.(png|jpg|)$/,
loader: 'url-loader?limit=200000'
},
]
},
plugins: [
new ExtractTextPlugin("styles.css"),
]
}
i'm using "webpack": "^2.7.0","#blueprintjs/core": "^1.34.1" and a lot of loaders
i tried to import my css like this
require('!css-loader!./index.css');
and just like this
import styles from './index.css'
the result is the same
after extra couple hours of work i got this error
at this point i'm not sure what's wrong with my webpack and how to fix it at all
any suggestions are welcome
You can compare your webpack configuration with the one in the Blueprint monorepo: https://github.com/palantir/blueprint/tree/develop/packages/webpack-build-scripts
Try applying loaders in the same order as in the base config: ['style-loader', 'css-loader', 'sass-loader']
Try using the full path to blueprint.css inside the NPM package. The webpack error in the screenshot clearly shows the css-loader trying to load esm/index.js, a JS file, so of course it fails.
Try: #import "~#blueprintjs/core/lib/css/blueprint.css";

Webpack: extract css to its own bundle

I'm using webpack on a project. I use style-loader so I can import "my.css".
The css gets bundled with the javascript and will be rendered in a <style> tag when component mount, ok.
However, I would like to keep that import syntax and make webpack build a css bundle for every entry point.
So webpack output should be [name].bundle.js AND [name].bundle.css.
Is this something I can achieve ?
var config = {
entry: {
'admin': APP_DIR + '/admin.entry.jsx',
'public': APP_DIR + '/public.entry.jsx'
},
output: {
path: BUILD_DIR,
filename: '[name].bundle.js'
},
resolve: {
extensions: ['.js', '.jsx', '.json']
},
plugins: [],
devtool: 'cheap-source-map',
module: {
loaders: [{
test: /(\/index)?\.jsx?/,
include: APP_DIR,
loader: 'babel-loader'
},
{
test: /\.scss$/,
loaders: [
'style-loader',
'css-loader',
'sass-loader',
{
loader: 'sass-resources-loader',
options: {
resources: ['./src/styles/constants.scss']
},
}
]
}
],
}
};
along with this babel.rc:
{
"presets" : ["es2015", "react"],
"plugins": ["transform-decorators-legacy", "babel-plugin-root-import"]
}
Yes, you need to use extract-text-webpack-plugin. You might want to do it only on your production config. Config looks like this:
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
module: {
rules: [
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
//resolve-url-loader may be chained before sass-loader if necessary
use: ['css-loader', 'sass-loader']
})
}
]
},
plugins: [
new ExtractTextPlugin('style.css')
//if you want to pass in options, you can do so:
//new ExtractTextPlugin({
// filename: 'style.css'
//})
]
}

2 bundles in webpack: 1 for js+css and 1 for css only

I've easily set up my webpack config for js+css and now I got stuck trying to update the config to generate a css-only bundle. The reason for this need is to separate bundles for landing page and the app itself. Here is my config (pretty much simplified but I kept everything that might be related):
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: [
'bootstrap-loader',
'./web/static/app/js/index.js'
],
output: {
path: './priv/static',
filename: 'js/app.js',
publicPath: '/',
},
module: {
loaders: [{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
plugins: ['transform-decorators-legacy'],
presets: ['react', 'es2015', 'stage-2', 'stage-0'],
}
}, {
test: /bootstrap\/dist\/js\/umd\//,
loader: 'imports?jQuery=jquery'
}, {
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style', 'css?localIdentName=[hash:base64]!autoprefixer?browsers=last 2 versions!sass')
}],
},
resolve: {
extensions: ['', '.js', '.scss', '.css'],
modulesDirectories: ["node_modules", __dirname + "/web/static/app/js"],
alias: {
styles: __dirname + '/web/static/app/styles'
}
},
plugins: [
new ExtractTextPlugin('css/[name].css')
]
};
currently it generates css/app.css and js/app.js just fine and what I'm trying to achieve is generating css/landing.css from web/static/landing/index.scss
What I've tried:
I added './web/static/landing/js/index.js' to module.exports.entry, added
var extractSCSS_app = new ExtractTextPlugin('css/app.css');
var extractSCSS_landing = new ExtractTextPlugin('css/landing.css');
and replaced scss loader with following:
}, {
test: /app\/.*?\.scss$/,
loader: extractSCSS_app.extract('style', 'css?localIdentName=[hash:base64]!autoprefixer?browsers=last 2 versions!sass')
}, {
test: /landind\/.*?\.scss$/,
loader: extractSCSS_landing.extract('style', 'css?localIdentName=[hash:base64]!autoprefixer?browsers=last 2 versions!sass')
}, {
and in plugins I've put
extractSCSS_app,
extractSCSS_landing,
Almost every article about webpack I've found describing js+css bundles configuration and docs are not clear to me regarding this question, so what I've tried is what I imagined could be right. Unfortunately it wasn't and that's why I'm here :)
Just quickly skimming through your question. could it be a typo. bring attention to this line
test: /landind\/.*?\.scss$/
landind instead of landing? late night coding haha?

Resources