Webpack favicons into different folder - webpack-3

I have two folders src/images/ and src/images/icons.
All favicons are in png format.
In src/images/icons I put all the favicons for different devices, which I want to be webpacked to wwwroot/images/icons and all other images to wwwroot/images.
How can I separate images and favicons?
Now for images I have:
{
test: /\.(png|ico|svg|jpg|gif)$/,
use: [
'file-loader?name=/images/[name].[ext]'
]
},
But this would copy all images to dist\images, including the icons, which should be one level deeper in folder dist\images\icons

There are several ways to do this (i.e. use test key against filename, separate rules, etc). However, here is one way that seems to work well and is fairly clear:
const path = require('path')
module.exports = {
// ...
module: {
rules: [
{
test: /\.(png|ico|svg|jpg|gif)$/,
exclude: /node_modules/,
use: {
loader: 'file-loader',
options: {
name: function(fullPath) {
return path.relative(__dirname + '/src', fullPath)
}
}
}
}
]
}
// ...
}

Related

Commitlint - Allow '/' in scope-enum

In my Angular project, I want to extend #commitlint/config-conventional with some pre-defined scopes.
The Angular project has a library for UI components (generated via ng generate library) and a default app which consumes the UI library.
In commitlint.config.js I've added the following lines:
module.exports = {
extends: ['#commitlint/config-conventional'],
rules: {
'scope-enum': [
2,
'always',
[
'ui-components',
'ui-components/badge',
'ui-components/button',
'ui-components/tooltip',
'core',
'account',
'plugins',
'settings',
'projects',
'shared',
'styles'
]
]
}
};
However, when I try to commit something with the scope: 'ui-components/tooltip':
fix(ui-components/tooltip): fix border
I get a commitlint error, saying that:
⧗ input: fix(ui-components/tooltip): fix border
✖ scope must be one of [ui-components, ui-components/badge, ui/button, ui-components/tooltip, core, account, plugins, settings, projects, shared, styles] [scope-enum]
✖ found 1 problems, 0 warnings
Unfortunately slashes aren't allowed in scopes.
To get around this I replace / with two dashes (--).
I wrote a script to grab subfolders and return an array:
https://gist.github.com/trevor-coleman/51f1730044e14081faaff098618aba36
[
'ui-components',
'ui-components--badge',
'ui-components--button',
'ui-components--tooltip',
...
]
According to source code, Commitlint use / for multiple scopes.
It means, you can commit like fix(core/account): fix border but you can't commit fix(ui-components/tooltip): fix border because you need to add tooltip in to your scopes first.
Here is source code: https://github.com/conventional-changelog/commitlint/blob/master/%40commitlint/rules/src/scope-enum.ts
Also, it is mentioned in here: https://github.com/conventional-changelog/commitlint/blob/master/docs/concepts-commit-conventions.md#multiple-scopes
You can write your own custom plugin to check scopes, I had the same issue, so I wrote one to solve this problem, see example commitlint.config.js below:
module.exports = {
extends: ["#commitlint/config-conventional"],
rules: {
"enhanced-scope-enum": [
2,
"always",
[
"ui-components",
"ui-components/badge",
"ui-components/button",
"ui-components/tooltip",
"core",
"account",
"plugins",
"settings",
"projects",
"shared",
"styles",
],
],
},
plugins: [
{
rules: {
"enhanced-scope-enum": (parsed, when = "always", value = []) => {
if (!parsed.scope) {
return [true, ""];
}
// only use comma sign as seperator
const scopeSegments = parsed.scope.split(",");
const check = (value, enums) => {
if (value === undefined) {
return false;
}
if (!Array.isArray(enums)) {
return false;
}
return enums.indexOf(value) > -1;
};
const negated = when === "never";
const result =
value.length === 0 ||
scopeSegments.every((scope) => check(scope, value));
return [
negated ? !result : result,
`scope must ${negated ? `not` : null} be one of [${value.join(
", "
)}]`,
];
},
},
},
],
}

Webpack - how to tell not compiling a js file for a specific entry point

Context
I am actually managing some dependencies via npm. Then I wrote a webpack.config.js to handle my imports :
Bundle Jquery + popper + Bootstrap.js
Bundle codemirror with my modules needs (xml autocomplete and so on)
...
Collect fonts from the fontawesome node_module
I am using django, so there is a collectstatic command which is helping me to collect all scripts, fonts, styles etc. to the folder I want. Everything is working great :
My bundled scripts are available
And for style sheets, I'm using relative imports to the 'vendor' node_module.
I am capable to get fonts to node_modules, and deliver it to the correct folder as expected.
Problem
I'm new to webpack world, and for sure I'm not using it as it should be, but it's working.
However when I run to compile my stuffs, an extra file is generated fontawesome.js in my fonts folder, is it possible to avoid this unexpected behavior.
What am I missing ?
It is not a big deal as long as I'm not importing this file, but I don't want to pollute my repo.
Edit
I updated the code of my webpack config.
Well, I figured out that the js file was generated from the filename in my entry point. But I don't want this file :)
wepback.config.js
"webpack": "^5.6.0",
var path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); // Extract css in its own file
const webpack = require('webpack');
const path_modules = path.resolve(__dirname, 'node_modules');
const base_path = path.resolve(__dirname, 'src');
const dist_static = path.resolve(__dirname, 'webpacked_src');
module.exports = {
entry: {
bootstrap: {
import: [
base_path + '/bootstrap/bootstrap-bundle.js',
//base_path + '/bootstrap/test.scss'
],
filename: 'js_packed/[name].js',
},
fontawesome: {
import: [
path_modules + '/#fortawesome/fontawesome-free/webfonts/fa-brands-400.eot',
//path_modules + '/#fortawesome/fontawesome-free/webfonts/fa-brands-400.svg',
path_modules + '/#fortawesome/fontawesome-free/webfonts/fa-brands-400.ttf',
path_modules + '/#fortawesome/fontawesome-free/webfonts/fa-brands-400.woff',
path_modules + '/#fortawesome/fontawesome-free/webfonts/fa-brands-400.woff2',
path_modules + '/#fortawesome/fontawesome-free/webfonts/fa-regular-400.eot',
//path_modules + '/#fortawesome/fontawesome-free/webfonts/fa-regular-400.svg',
path_modules + '/#fortawesome/fontawesome-free/webfonts/fa-regular-400.ttf',
path_modules + '/#fortawesome/fontawesome-free/webfonts/fa-regular-400.woff',
path_modules + '/#fortawesome/fontawesome-free/webfonts/fa-regular-400.woff2',
path_modules + '/#fortawesome/fontawesome-free/webfonts/fa-solid-900.eot',
//path_modules + '/#fortawesome/fontawesome-free/webfonts/fa-solid-900.svg',
path_modules + '/#fortawesome/fontawesome-free/webfonts/fa-solid-900.ttf',
path_modules + '/#fortawesome/fontawesome-free/webfonts/fa-solid-900.woff',
path_modules + '/#fortawesome/fontawesome-free/webfonts/fa-solid-900.woff2',
],
filename: 'fonts/[name].js'
},
codemirror: {
import: [
base_path + '/codemirror/code-mirror.js',
path_modules + '/codemirror/lib/codemirror.css',
path_modules + '/codemirror/theme/monokai.css', // Import the theme style --> Little selection midnight / material-darker / material-ocean / monokai (sublimetext)
path_modules + '/codemirror/addon/hint/show-hint.css',
],
filename: 'js_packed/[name].js',
},
vue: {
import: [
base_path + '/vue/vue.js',
],
filename: 'js_packed/[name].js',
},
},
output: {
path: dist_static
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
}),
autoprefixer = require('autoprefixer'),
new MiniCssExtractPlugin({
filename: "css_packed/[name].css", // change this RELATIVE to the output.path
}),
],
module: {
rules: [
{
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/'
}
}
]
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader, // instead of style-loader
'css-loader'
]
},
{
test: /\.scss$/,
exclude: /node_modules/,
use: [
{
loader: 'file-loader',
options: {outputPath: 'css/', name: '[name].min.css'}
},
'sass-loader'
]
}
],
},
};
fontawesome.js
And the content of the generated file, if it can help webpack experts :
(() => {
"use strict";
var t = {};
t.g = function () {
if ("object" == typeof globalThis) return globalThis;
try {
return this || new Function("return this")()
} catch (t) {
if ("object" == typeof window) return window
}
}(), (() => {
var r;
t.g.importScripts && (r = t.g.location + "");
var e = t.g.document;
if (!r && e && (e.currentScript && (r = e.currentScript.src), !r)) {
var p = e.getElementsByTagName("script");
p.length && (r = p[p.length - 1].src)
}
if (!r) throw new Error("Automatic publicPath is not supported in this browser");
r = r.replace(/#.*$/, "").replace(/\?.*$/, "").replace(/\/[^\/]+$/, "/"), t.p = r + "../"
})(), t.p, t.p, t.p, t.p, t.p, t.p, t.p, t.p, t.p, t.p, t.p, t.p
})();
Unfortunately, this is a bug in webpack: https://github.com/webpack/webpack/issues/11671
In the meantime, it's straight forward to add a custom webpack plugin that will remove these files. Here's what I'm using to delete all JS files (because I'm using a CSS file as my entry):
plugins: [
{
// Delete empty JS files; work around for https://github.com/webpack/webpack/issues/11671
apply: (compiler) => {
compiler.hooks.afterEmit.tap('DeleteJSFilesPlugin', (compilation) => {
const iter = compilation.emittedAssets.entries();
for (const [key] of iter) {
if (key.match(/.*\.js$/)) {
fs.unlinkSync(path.join(compilation.outputOptions.path, key));
}
}
});
}
}
]

Vue.js: Is it possible to do "Conditional compilation" with a Vue project?

In for example Swift/iOS development, it's possible to differentiate builds for different environments with "flags" such as:
#if STAGING
// one set of logic here
#endif
#if PRODUCTION
// another set of logic here
#endif
Is it possible to achieve the same with a Vue.js project, and how would we go about doing it? I am aware of makes different routes conditionally available for different roles (which is also quite neat), but I am optimally looking for the option to differentiate on a source code level.
Hope someone has some great insights! It could include:
How to exclude parts of a file (such as the #if STAGING above) from a build target
How to exclude entire files from a build target
etc.
you have the ability to use this syntax
if(process.env.NODE_ENV === 'production') {
console.log("this is the prod env!!!!!!!!!!");
config.output.path = path.resolve(__dirname, "dist");
}
make sure that when you run the script with the correct env's for each environment (local, dev, staging, prod etc ..) :D
just change the vue-loader output.
the source code
<template v-if="process.env.NODE_ENV === 'development'">
development only
</template>
default output
var render = function() {
var _vm = this
var _h = _vm.$createElement
var _c = _vm._self._c || _h
return _c(
"div",
{ attrs: { id: "app" } },
[
_vm.process.env.NODE_ENV === "development"
? [_vm._v(" development only ")]
: _vm._e(),
_c("router-view")
],
2
)
}
just use regex to replace _vm.process.env. by process.env is ok.
// webpack.config.js
module: {
rules: [{
// must set post
enforce: 'post',
test: /\.vue$/,
use: [{
loader: './myLoader'
}]
}]
}
// myLoader.js
module.exports = function (source, map) {
if (source.indexOf('_vm.process.env') > -1) {
source = source.replace(/_vm.process.env/g, 'process.env')
}
this.callback(
null,
source,
map
)
}
Final the vue-loader result change
var render = function() {
var _vm = this
var _h = _vm.$createElement
var _c = _vm._self._c || _h
return _c(
"div",
{ attrs: { id: "app" } },
[
// change to true
true
? [_vm._v(" development only ")]
: undefined,
_c("router-view")
],
2
)
}

How to remap a Durandal viewmodel

This is my main.js file in a Durandal project.
What I'm trying to do is set things up so that the name 'upload-item' resolves to either 'upload-item' or 'upload-item-prehtml5' depending on whether File is defined.
requirejs.config({
paths: {
'text': '../lib/require/text',
'durandal': '../lib/durandal/js',
'plugins': '../lib/durandal/js/plugins',
'transitions': '../lib/durandal/js/transitions',
'knockout': '../lib/knockout/knockout-2.3.0',
'bootstrap': '../lib/bootstrap/js/bootstrap',
'jquery': '../lib/jquery/jquery-1.9.1.min',
'jquery-ui': '../lib/jquery-ui/jquery-ui-1.10.4.custom/js/jquery-ui-1.10.4.custom.min',
'moment': '../lib/moment/moment',
'knockout-jqueryui': '../lib/knockout/knockout-jqueryui.min',
'file-size-formatting': '../lib/wone/file-size-formatting'
},
shim: {
'bootstrap': {
deps: ['jquery'],
exports: 'jQuery'
}
}
});
define(['durandal/system', 'durandal/app', 'durandal/viewLocator'], function (system, app, viewLocator) {
//>>excludeStart("build", true);
system.debug(true);
//>>excludeEnd("build");
var filetype = typeof(File);
if (filetype == 'undefined') {
//apply pre-html5 fixups
require.config({
map: {
'*': {
'upload-item': 'upload-item-prehtml5'
}
}
});
}
app.title = 'Jumbo File Transfer';
//specify which plugins to install and their configuration
app.configurePlugins({
router: true,
dialog: true,
widget: {
kinds: ['expander']
}
});
app.start().then(function () {
//Replace 'viewmodels' in the moduleId with 'views' to locate the view.
//Look for partial views in a 'views' folder in the root.
viewLocator.useConvention();
//Show the app by setting the root view model for our application.
app.setRoot('shell');
});
});
Testing on IE8 shows that the call to require.config occurs and the mapping is added, but it doesn't seem to have the effect I expected: upload-item.js and upload-item.html are loaded when I expected upload-item-prehtml5.js and upload-item-prehtml5.html to be loaded.
If this is the wrong way to go about this, then what is the right way to perform this kind of conditional resolution?
It's not quite what I originally wanted, but I found you can do this:
var prehtml5 = (typeof (File) == 'undefined');
requirejs.config({
paths: {
...
'upload-item': prehtml5 ? 'upload-item-prehtml5' : 'upload-item'
},
shim: {
'bootstrap': {
deps: ['jquery'],
exports: 'jQuery'
}
}
});
Path remapping seems to extend into the file name. Normally you wouldn't list siblings of main.js but you can and if you do then you can remap them, including the file name.

i18next - All languages in one .json file

How can I make i18next load all languages from just one file?
I managed to do it by putting each language in a seperate file (translation-en.json, translation-no.json, etc), and also managed to input languages with the resStore option, but putting it all in a seperate .json file is really not documented anywhere (I've searched for 4 hours+ now)
My js code:
i18n.init({
debug: true,
lng: 'en',
resGetPath: 'translation.json'
},
function(t) {
console.log(t('test'));
});
My translation.json file:
{
en: {
translation: {
test: "some string"
}
},
no: {
translation: {
test: "litt tekst"
}
}
}
Ok, so I managed to "hack" it byt putting an object into a seperate .js file, include it in a script tag and loading it using resStore, but that just can't be the best way to use this lib.
Assume that your translation.json has loaded and assigned to a variable named resStore:
var resStore = {
en: {
translation: {
test: "some string"
}
},
no: {
translation: {
test: "litt tekst"
}
}
};
Next, you can override default ajax loading functionality with your customLoad function. An example might look like this:
var options = {
lng: 'en',
load: 'current',
lowerCaseLng: true,
fallbackLng: false,
resGetPath: 'i18n/__lng__/__ns__.json',
customLoad: function(lng, ns, options, loadComplete) {
var data = resStore[lng][ns];
loadComplete(null, data); // or loadComplete('some error'); if failed
},
ns: {
namespaces: ['translation'],
defaultNs: 'translation'
}
};
i18n.init(options, function(t) {
t('test'); // will get "some string"
});
new update on Mar 20, 2015
You can simply pass your resource store with the resStore option:
i18n.init({ resStore: resources });