Nuxt - Custom icon-font not served from _nuxt folder - vuejs2

I have successfully used the webfonts-loader package to generate a font and class-definitions for icons, but it isn't served by my nuxt dev server. There is a styletag in my head with:
#font-face {
font-family: "TopLoggerIcons";
src: url("/myfont.eot?#iefix") format("embedded-opentype"), url("/myfont.woff2") format("woff2");
}
But the requested http://localhost:3010/myfont.woff2 gives a 404. I had this working in the nuxt version before 2.0 (and before webpack 4), where the file is served from http://localhost:3010/_nuxt/myfont.woff2. The font is currently also served from there, but the path in the font-face declaration is wrong. I'm wondering what has changed here removing the (required?) _nuxt part in the path.
In my nuxt.config.js file I have:
build: {
extend(config, ctx) {
config.module.rules.push({
test: /plugins\/icons\.js$/,
use: ['vue-style-loader', 'css-loader', 'webfonts-loader'],
})
},
}
Now according to the example on the webfonts-loader lib I need to use the MiniCssExtractPlugin.loader instead of the vue-style-loader, but that doesn't work. I read here that it is internally used by nuxt, but i don't know how to add it here.
Hope anyone has an idea where to look...

Ok, just figured it out: you have to use the publicPath option of the webfonts-loader package:
extend(config, ctx) {
config.module.rules.push({
test: /plugins\/icons\.js$/,
use: [
'vue-style-loader',
'css-loader',
{
loader: 'webfonts-loader',
options: {
publicPath: config.output.publicPath,
},
}
],
})
}
The config.output.publicPath is /_nuxt/.

Related

Image URLs don't resolve in Vue component

My problem :
Path generated for images are the same for images used in css or in a vue component.
Images are correctly loaded from CSS files, but are not found when declared in a vue component.
Version of webpack : 3.6.0
Here is the webpack configuration
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
publicPath: '../../',
limit: 1000,
name: utils.assetsPath('images/[name].[hash:7].[ext]')
}
},
{
test: /\.css$/,
use: [
'vue-style-loader',
{
loader: 'css-loader',
options: {
modules: true,
name: utils.assetsPath('css/[name].[ext]'),
}
},
]
}
sourceMap is enabled and publicPath is './'
All works correctly if files are deployed in server root directory, but it is deployed in a subdirectory, it doesn't.
Let's say I deploy my files in a 'dev' subdirectory.
Images in CSS files will be search in /dev/static/images/
Images in vue components will be searched in /static/images/, where they won't be found...
I can't figure out what I am doing wrong... Any help or advice is appreciated.
Thanks !

Webpack, Scss - add cdn server path before compilation

How do I add a cdn path variable into the styles.scss before compilation? I have a webpack 4 configuration that works fine for JS. The JS/CSS files are loaded correctly from the desired cdn url.
What I want to achieve is, that the project running on localhost will use a different cdn url for images/icons/fonts than the same web running on production.
My webpack config has these lines for setting the cdn domain:
if (process.env.NODE_ENV === 'production') {
webUrl = 'https://cdn.project.com/';
}
else if (process.env.NODE_ENV === 'development') {
webUrl = 'http://localcdn.localhost/';
}
This code works well for JS/CSS files, but CSS always loads backgrounds/fonts using a relative path, which of course is the main domain and not the cdn.
Maybe just open the styles.scss and update the file manually before webpack compilation? Isn't there a better way?
After hours of trial and error I found this solution for webpack 4. It may help someone trying to solve the same issue.
{
test: /\.(sa|sc|c)ss$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options : {
url : false,
sourceMap: devMode
}
},
{
loader: 'sass-loader',
options : {
processCssUrls : false,
sourceMap: devMode,
data : "$cdnFolder: 'http://cdn.myweb.net/';"
}
}
],
},
This is a part of webpack.config.js, in the section:
module : {
rules : {
This configuration makes the scss variable $cdnFolder available in every scss file. CDN link can be changed based on the current mode dev/prod/stage.
For webpack 5, the config changed a little:
{
loader: 'sass-loader',
options : {
additionalData : "$cdnFolder: '" + cdnUrl + "';"
}
}

responsive-loader with nuxt.js

I want to integrate responsive-loader into my Nuxt.js project which runs in SPA mode. (Optional I want to add Vuetify Progressive Image support also).
It will be a static hosting with Netlify.
Versions:
"nuxt": "^2.3.4"
"responsive-loader": "^1.2.0"
"sharp": "^0.21.1"
I found some solutions how to do it (https://stackoverflow.com/a/51982357/8804871) but this is not working for me.
When I run npm run build
I get an error message: "TypeError: Cannot set property 'exclude' of undefined"
My build section looks the following:
build: {
transpile: [/^vuetify/],
plugins: [
new VuetifyLoaderPlugin()
],
extractCSS: true,
/*
** Run ESLint on save
*/
extend(config, { isDev, isClient, isServer }) {
// Default block
if (isDev && isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
if (isServer) {
config.externals = [
nodeExternals({
whitelist: [/^vuetify/]
})
]
}
// Default block end
// here I tell webpack not to include jpgs and pngs
// as base64 as an inline image
config.module.rules.find(
rule => rule.loader === "url-loader"
).exclude = /\.(jpe?g|png)$/;
/*
** Configure responsive-loader
*/
config.module.rules.push({
test: /\.(jpe?g|png)$/i,
loader: "responsive-loader",
options: {
min: 350,
max: 2800,
steps: 7,
placeholder: false,
quality: 60,
adapter: require("responsive-loader/sharp")
}
});
}
}
The error is probably found in this section:
config.module.rules.find(
rule => rule.loader === "url-loader"
).exclude = /\.(jpe?g|png)$/;
Like said I get this error message: "TypeError: Cannot set property 'exclude' of undefined".
I run this project along with vuetify. I also would like to enable the Progressive image support together with responsive loader. Does anybody know how to setup both rules together?
https://github.com/vuetifyjs/vuetify-loader#progressive-images
The easiest way to integrate responsive-loader into a Nuxt.js project is to use this module: https://www.npmjs.com/package/nuxt-responsive-loader
Disclaimer: I created the module
The problem with your config that it relies on rule.loader property but rule can be defined in use or oneOf config sections as well.
Another one problem is that nuxt internal config has several rules with url-loader(for images, videos, fonts ...).
In your case the rule, you tried to find, has use section and url-loader is defined there, that's why your find function found nothing and threw this error:
{
"test": /\.(png|jpe?g|gif|svg|webp)$/,
"use": [{
"loader": "url-loader",
"options": {
"limit": 1000,
"name": "img/[hash:7].[ext]"
}
}]
}
About responsive-loader, you should remove extensions you want to process with responsive-loader from url-loader rule to avoid unexpected behavior and conflicts, here is extend function working example:
extend(config, ctx) {
let imgTest = '/\\.(png|jpe?g|gif|svg|webp)$/';
// find by reg ex string to not rely on rule structure
let urlRule = config.module.rules.find(r => r.test.toString() === imgTest);
// you can use also "oneOf" section and define both loaders there.
// removed images from url-loader test
urlRule.test = /\.(svg|webp)$/;
config.module.rules.push({
test: /\.(png|jpe?g|gif)$/,
loader: "responsive-loader",
options: {
// place generated images to the same place as url-loader
name: "img/[hash:7]-[width].[ext]",
min: 350,
max: 2800,
steps: 7,
placeholder: false,
quality: 60,
adapter: require("responsive-loader/sharp")
}
})
}
Yes, it looks dirty, but I think it's only way for now to change some loader.
What about vuetify - I think both loaders will conflict with each other and probably the solution is to use single loader that will work with your images.
Hope it helps.
Update for Nuxt >= 2.4.0:
They modified the rules array please update the following line:
let imgTest = '/\\.(png|jpe?g|gif|svg|webp)$/i';
Then the code should work normally again.

Two compile cases with Webpack, Vue.js, and Sass

I'm using Webpack (v4), Sass and Vue.js (v2) in my project.
In some cases, I'd like to compile sass code into .css files. (This is for the .scss files that are mentioned in webpack.config.js as "entry" points)
In some other cases I'd like to have the compiled sass code injected into a html tag. (This is for the <style lang="sass"> included in my .vue single file components)
Is it possible to have both at the same time? How should I configure Webpack?
You can use sass-loader to include scss files anywhere and compile them:
https://github.com/webpack-contrib/sass-loader
To include scss in a single-file-component, you don't have to do anything specific, just write your styles into a style tag specifying lang="scss".
Here is a detailed example for both cases:
https://medium.com/hong-kong-tech/use-sass-scss-of-webpack-in-vuejs-8dde3a83611e
You can only leave scss files for webpack to process. You can't get them processed during build time and inject them into your single components, as stated here "In some other cases I'd like to have the compiled sass code injected into a html tag. (This is for the included in my .vue single file components)".
You have to leave to webpack the burden to compile all your scss files into css. Then you choose to either extract them or leave them in the html style tag.
Sorry PlayMa256 & Máté, for being so long before answering your replies.
In the end I found the solution of using two different configurations for my two cases. Webpack allows it through its multi-compiler feature.
So here is what my webpack.config.js now looks like:
module.exports = [ // notice that we are handling an array of configurations here
// In this first config, I manage the first of my use cases:
// Compilation of .scss files into .css files
{
name: "css",
entry: { /* ... */ },
output: { /* ... */ },
/* ... */
module: {
rules: [
{
test: /\.scss$/,
use: [ MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'sass-loader' ],
}
]
},
plugins: [ /* ... */]
},
// In this other config, I manage the other of my use cases:
// injection of the <style> blocks of my .vue files into the DOM
{
name: "main", // name for first configuration
entry: { /* ... */ },
output: { /* ... */ },
/* ... */
module: {
rules: [
// Vue single file components loader
{
test: /\.vue$/,
loader: 'vue-loader',
},
// Injection of <style> elements into the DOM,
// for both plain `.css` files and `<style>` blocks in `.vue` files
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
]
},
// Compilation of sass code,
// (This actually works both for `.css` files and `<style>` blocks in `.vue` files,
// but I don't have any `.css` as entry for this config.)
{
test: /\.scss$/,
use: [
"style-loader", // creates style nodes from JS strings
"css-loader", // translates CSS into CommonJS
"sass-loader" // compiles Sass to CSS, using Node Sass by default
]
}
]
},
plugins: [ /* ... */]
}
];

npm - package.json override main field

I use some npm packages in my project. Two of them have the wrong main-field. Is it possible to override them?
I use webpack. I found a solution here.
This works for the main field but I also need a css-file from the same package. I refer it with ~package/css/style.css in my index.scss file. With the solution above it resolves the path with path/to/main.js/css/style.css (with main.js) instead of path/to/css/style.css (without main.js).
I could refer it directly ../node_modules/path/to/css/style.css but I think thats ugly.
So is there an other solution with webpack or npm to override this main field?
-- EDIT --
I use bootstrap-treeview as package. I refer it in index.scss like so
#import '~bootstrap-treeview/src/css/bootstrap-treeview.css';. This works.
When I add 'bootstrap-treeview': path.join(_path, 'node_modules', 'bootstrap-treeview', 'src', 'js', 'bootstrap-treeview.js') as alias in webpack import 'bootstrap-treeview'; works but the css not (as describes above).
-- EDIT 2 --
webpack.conf.js:
resolve: {
extensions: ['', '.js'],
modulesDirectories: ['node_modules'],
alias: {
// bootstrap-treeview alias
'bootstrap-treeview': path.join(_path, 'node_modules', 'bootstrap-treeview', 'src', 'js', 'bootstrap-treeview.js')
}
},
module: {
loaders: [
{
test: /\.css$/,
loaders: [
'style-loader',
'css-loader?sourceMap',
'postcss-loader'
]
},
{
test: /\.(scss|sass)$/,
loader: 'style-loader!css-loader?sourceMap!postcss-loader!sass-loader?outputStyle=expanded&sourceMap=true&sourceMapContents=true
}
]
}
index.scss see above.
Error with bootstrap-treeview alias:
Module not found: Error: Cannot resolve 'file' or 'directory' /home/ekf/develop/generator-angular-webpack/node_modules/bootstrap-treeview/src/js/bootstrap-treeview.js/src/css/bootstrap-treeview.css in ...
Error without alias:
Module not found: Error: Cannot resolve module 'bootstrap-treeview' in ...
just in case
webpack scss loader config
module: {
loaders: [
{
test: /\.css$/,
exclude: /node_modules/,
loader: "style-loader!css-loader"
},
{
test: /\.scss$/,
exclude: /node_modules/,
loader: "style-loader!css-loader!sass-loader"
}
]
}
The problem is that your alias points directly to the JS file, instead of pointing to the common ancestor of both the JS and the CSS. It's nice and convenient to be able to import Treeview from "bootstrap-treeview" but it leads to the problem you're describing.
Instead, you could specify a higher level alias:
resolve: {
alias: {
// bootstrap-treeview alias
'bootstrap-treeview': path.join(_path, 'node_modules', 'bootstrap-treeview', 'src')
}
},
and get the JS as import Treeview from "boostrap-treeview/js/bootstrap-treeview.js". This allows you to get the CSS as require("bootstrap-treeview/css/bootstrap-treeview.css").
You might be able to get clever about it and tell Webpack to look for CSS files in ~/css/ and JS files in ~/js/ but that would be adding more magic for (IMHO) little gain.