How do I add an additional postcss plugin via the new #angular/cli v7 angular.json or custom-webpack.config.js? - angular7

#angular/cli#7+ allows a customWebpackConfig to be specified to provide custom webpack configuration, such as:
"architect": {
"build": {
"builder": "#angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig": {
"path": "./build/custom-webpack.config.js",
"mergeStrategies": {
"externals": "prepend"
}
},
...
This file then technically allows you to prepend, append or replace any portion of the webpack configuration. Prior to upgrading to #angular#7.1.3 and #angular/cli#7.1.3 we had ejected the webpack configuration to make some additions. One such addition was the postcss-momentum-scrolling postcss-loader plugin that automatically enabled iOS momentum scrolling on all scrollable containers.
I am seeking support on figuring out how to generate the necessary custom webpack code to load this plugin via the supported customizations allowed by #angular/cli#7+.
Here is a sample of what I have tried in my custom-webpack.config.js file:
const postcssMomentumScrolling = require('postcss-momentum-scrolling');
module.exports = {
module: {
rules: [
{
test: /\.scss$|\.sass$/,
use: [
{
"loader": "postcss-loader",
"options": {
"plugins": [
postcssMomentumScrolling(),
]
}
}
]
},
],
},
};
As soon as I touch the scss chunk of the webpack config, it seems to do a replace instead of a merge or prepend, breaking the build.
I am wondering if anyone has a guide or suggestions on how to see what the initial webpack configuration that #angular/cli generates that is the starting point for modifications and a way to preview/peek at the code to be executed as debugging.
Also, an example of a similar customization would be great.
Thanks!

I think you need to tell to "customWebpackConfig" which portion to merge. Like this:
"mergeStrategies": {
"module.rules": "prepend"
}
In this way you're going to tell to merge with prepend strategy.
According to "custom-webpack" documentation it should default to "append" which doesn't seem the case in your example.
It's been a while since you've put the question but I wanted to actually ask if you have been able to fix it since I'm running in some issues getting my "module.rules" merged...it seems to work only if I set "replace" strategy.

Related

How to disable strictMode in Babel.confict.js for Rails? [duplicate]

I'm using function form of "use strict" and don't want global form which Babel adds after transpilation. The problem is I'm using some libraries that aren't using "use strict" mode and it might throw error after scripts are concatenated
As it has already been mentioned for Babel 6, it's the transform-es2015-modules-commonjs preset which adds strict mode.
In case you want to use the whole es2015 preset without module transformations, put this in your .babelrc file:
{
"presets": [
["es2015", { "modules": false }]
]
}
This will disable modules and strict mode, while keeping all other es2015 transformations enabled.
Babel 5
You'd blacklist "useStrict". For instance here's an example in a Gruntfile:
babel: {
options: {
blacklist: ["useStrict"],
// ...
},
// ...
}
Babel 6
Since Babel 6 is fully opt-in for plugins now, instead of blacklisting useStrict, you just don't include the strict-mode plugin. If you're using a preset that includes it, I think you'll have to create your own that includes all the others, but not that one.
There's now a babel plugin that you can add to your config that will remove strict mode: babel-plugin-transform-remove-strict-mode. It's a little ugly in that the "use strict" gets added and then removed, but it makes the config much nicer.
Docs are in the GitHub repo:
https://github.com/genify/babel-plugin-transform-remove-strict-mode
Your .babelrc ends up looking like this:
{
"presets": ["env"],
"plugins": ["transform-remove-strict-mode"]
}
I also came accross this rather ridiculous limitation that you cannot disable or overwrite settings from an existing preset, and have resorted to using this preset instead: https://www.npmjs.com/package/babel-preset-es2015-without-strict
plugins: [
[
require("#babel/plugin-transform-modules-commonjs"),
{
strictMode: false
}
],
]
You can tell babel that your code is a script with:
sourceType: "script"
in your babel config file. This will not add use strict. See sourceType option docs
Source: https://github.com/babel/babel/issues/7910#issuecomment-388517631
Babel 6 + es2015
We can disabled babel-plugin-transform-es2015-modules-commonjs to require babel-plugin-transform-strict-mode.
So comment the following code in node_modules/babel-plugin-transform-es2015-modules-commonjs/lib/index.js at 151 line
//inherits: require("babel-plugin-transform-strict-mode"),
just change .babelrc solution
if you don't want to change any npm modules, you can use .babelrc ignore like this
{
"presets": ["es2015"],
"ignore": [
"./src/js/directive/datePicker.js"
]
}
ignore that file, it works for me!
the ignored file that can't use 'use strict' is old code, and do not need to use babel to transform it!
Personally, I use the gulp-iife plugin and I wrap IIFEs around all my files. I noticed that the babel plugin (using preset es2015) adds a global "use strict" as well. I run my post babel code through the iife stream plugin again so it nullifies what babel did.
gulp.task("build-js-source-dev", function () {
return gulp.src(jsSourceGlob)
.pipe(iife())
.pipe(plumber())
.pipe(babel({ presets: ["es2015"] }))// compile ES6 to ES5
.pipe(plumber.stop())
.pipe(iife()) // because babel preset "es2015" adds a global "use strict"; which we dont want
.pipe(concat(jsDistFile)) // concat to single file
.pipe(gulp.dest("public_dist"))
});
This is not grammatically correct, but will basically work for both Babel 5 and 6 without having to install a module that removes another module.
code.replace(/^"use strict";$/, '')
Since babel 6 you can install firstly babel-cli (if you want to use Babel from the CLI ) or babel-core (to use the Node API). This package does not include modules.
npm install --global babel-cli
# or
npm install --save-dev babel-core
Then install modules that you need. So do not install module for 'strict mode' in your case.
npm install --save-dev babel-plugin-transform-es2015-arrow-functions
And add installed modules in .babelrc file like this:
{
"plugins": ["transform-es2015-arrow-functions"]
}
See details here: https://babeljs.io/blog/2015/10/31/setting-up-babel-6
For babel 6 instead of monkey patching the preset and/or forking it and publishing it, you can also just wrap the original plugin and set the strict option to false.
Something along those lines should do the trick:
const es2015preset = require('babel-preset-es2015');
const commonjsPlugin = require('babel-plugin-transform-es2015-modules-commonjs');
es2015preset.plugins.forEach(function(plugin) {
if (plugin.length && plugin[0] === commonjsPlugin) {
plugin[1].strict = false;
}
});
module.exports = es2015preset;
Please use "es2015-without-strict" instead of "es2015". Don't forget you need to have package "babel-preset-es2015-without-strict" installed. I know it's not expected default behavior of Babel, please take into account the project is not mature yet.
I just made a script that runs in the Node and removes "use strict"; in the selected file.
file: script.js:
let fs = require('fs');
let file = 'custom/path/index.js';
let data = fs.readFileSync(file, 'utf8');
let regex = new RegExp('"use\\s+strict";');
if (data.match(regex)){
let data2 = data.replace(regex, '');
fs.writeFileSync(file, data2);
console.log('use strict mode removed ...');
}
else {
console.log('use strict mode is missing .');
}
node ./script.js
if you are using https://babeljs.io/repl (v7.8.6 as of this writing), you can remove "use strict"; by selecting Source Type -> Module.
Using plugins or disabling modules and strict mode as suggested in the #rcode's answer didn't work for me.
But, changing the target from es2015|es6 to es5 in tsconfig.json file as suggested by #andrefarzart in this GitHub answer fixed the issue.
// tsconfig.json file
{
// ...
"compilerOptions": {
// ...
"target": "es5", // instead of "es2015"
}

Electron: Keep Getting 'You'll need a new app to open this' Screen

Developed an Electron app using Vuejs and everything works fine in development, but when packaged I keep getting this pop-up after start up (NOTE: This is a sample image - mine doesn't say 'windowsdefender' but is otherwise the same).
Using electron-builder to create the application with the following build json, and it is installed on the PC:
{
"productName": "My App",
"appId": "com.mycompany.myapp",
"win": {
"icon": "build/icon.png",
"target": [
"nsis"
]
}
}
Though the app does open, there is no initial screen. However, I can open the dev tools but there are no errors displayed.
Any ideas on what is causing this or how to resolve?
After many tries, I finally figured it out (or at least I think I know what caused the issue).
The primary issue was that in using vue router (from an app ported from the web), it is important that you use 'hash' mode and not 'history. Add this to your router file:
const router = new VueRouter({
mode: process.env.IS_ELECTRON ? "hash" : "history",
routes
});
See this link for more details (common issues): Vue CLI plugin common issues
Second, I think there is a rights issue (i.e. having elevated rights to install) so I added this line along with the guid to my electron-builder.json file. The result was a build file like this:
{
"productName": "My App",
"appId": "com.abcco.my-app",
"win": {
"icon": "build/icon.png",
"target": "nsis",
"requestedExecutionLevel": "requireAdministrator"
},
"nsis": {
"guid": "6ee647a9-d5c6-46a9-a480-aa7d6d3d1c10",
"oneClick": false,
"allowToChangeInstallationDirectory": true
}
}
As I am developing only for Windows I was able to use material from this page (React but not that different with respect to Electron packaging):
Electron Build file help
The last thing I did was to remove all 'dist' files and uninstall the app entirely (previous versions). I think this cleared up a lot of the 'baggage' left over from testing.
Hopefully this helps others who may experience the same issue.

Webpack 2: CommonsChunkPlugin issue

I would like to ask a question about CommonsChunkPlugin
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: {
vendor: ['moment'],
app: ['./www/build/main.js']
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].bundle.js'
},
module: {
rules: [
{ test: /\.(js)$/, use: 'babel-loader' }
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'chunk'
})
]
}
After i run the webpack script, there are 3 files generated (vendor.bundle, app.bundle, chunk.bundle). My questions are:
What is the usage chunk.bundle and why it is generated? I set the config in "entry" and output is depends on the [name] of entry
How can i run the script to all files under a folder? The current setting needs to input one by one.
If my file is too large, how can i split is into some smaller files?
Thanks.
1) The chunk.bundle.js is being generated by the plugin. It operates a little outside of the usual Webpack flow.
2) Not sure what you're getting at, here. You probably need to look at the minChunks setting, or chunks.
3) You can use multiple instances of the plugin. I've found that you have to use the chunks setting on every instance except for one to avoid getting an error. Basically that specifies on what entry files the plugin will operate. You can specify all your entry files in chunks, and then use a function with minChunks to filter out what you want to include in that file.

How to get (tray) icon path/image in electron-builder

I'm using electron-react-boilerplate to develop electron app (which uses electron-builder to pack apps).
I want to create tray, but it requires icon path or native image. The question is how to retrieve icon image from electron-builder or how to tell electron-builder to include icons dir into resources (without packing), so I can use:
appIcon = new Tray(iconPath | nativeImage)
I kind of struggled with a solution about non-packaged assets (such as media or JSON config files), mostly because I was not familiar with Electron until now. :)
I built a simple personal tray-only app and I didn't want to repackage every time I change an icon for instance.
If you too plan on using changing/dynamic assets you can distinguish between "development" and "production" using this property:
https://electronjs.org/docs/api/app#appispackaged-readonly
Make sure you have this in your package.json:
"build": {
...
"extraResources": [
"./assets/**"
],
}
https://www.electron.build/configuration/contents#extraresources
Then in your code you can have:
const assetsPath = app.isPackaged ? path.join(process.resourcesPath, "assets") : "assets";
Of course you can also use a different path for storing assets, independent of your packaged app folder, for example your user's home or user's documents:
https://electronjs.org/docs/api/app#appgetpathname
Electron v7.0.1
electron-builder 21.2.0
Firstly you need to tell electron-builder which extra files need copying into your output build. I copy over native drivers for each os like below, but you should be able to adapt this to your needs. The "to": "resources" means you'll be able to use the next code to find the files later.
"build": {
...
"extraFiles": [
{
"from": "resources/${os}/drivers",
"to": "resources",
"filter": [
"**/*"
]
}
],
Then to get access to that path from in electron you can use:
const path = require('path');
const imgPath = path.join(process.resourcesPath, 'image.png')
If you're in the main process you can omit the remote part.
You can then use nativeImage.createFromPath to get a native image:
const nativeImage = require('electron').nativeImage
let image = nativeImage.createFromPath(imgPath)
Thanks, Tim, your answer gave me a good thought. I reused it with some addition depending on how I run my app - form vs code using electron or from installed deb file:
"build": {
...
"extraFiles": [
{
"from": "assets",
"to": "resources",
"filter": [
"**/*"
]
}
]
...
}
And then:
let imgPath = process.env.DEV ? "assets/icon.png" : path.join(process.resourcesPath, "icon.png");
tray = new Tray(imgPath);

Gulp task to bundle bower_components?

I'd appreciate it so much if someone could please tell me a good way to handle bundling bower components. I feel like I've tried everything... Although, I can't seem to find any gulp tasks that handle this already. Could it really not exist?
Let's say it doesn't exist. Worst case scenario is I have to specify the paths of each "dist" file from bower_components folder. (It is annoying that each component seems to have its own "dist" folder... nothing is standardized.)
So even if I do that, I've noticed some components like 'active-support' seem to have require('lodash') and such in them. I think that if I just simply copy that file, it will break because the requires won't resolve.
What am I missing? How do I simply take all bower_components and bundle into a "common.js"... is there a way or is it a clusterfluck?
Update
As pointed out by Alerty, the new Gulp policy seems to be: use bower directly and glob patterns (and hope that the packages maintainers have a proper "ignore" properties).
Previously
You can use main-bower-files or gulp-bower-src to get files from your bower components. They can also use "ignore" or "main" overrides in your own bower file.
This is how I managed it (but see gulpfile.js for project structure, it's not a single gigantic gulpfile) :
https://github.com/notbrain/viceroy/blob/master/gulp/tasks/bower.js
Would be a bit more modular to simply concat all bower deps and then do the uglify() and minifyCSS() tasks separately on dist/ source locations, based on dev/prod env targets, but will have to wait for future updates.
Use main-bower-files:
var gulp = require('gulp');
var mainBowerFiles = require('main-bower-files');
gulp.task('TASKNAME', function() {
return gulp.src(mainBowerFiles())
.pipe(/* what you want to do with the files */)
});
if you have folders like:
-app
-bower
-node_modules
Gulpfile.js
package.json
the solution are:
gulp.task("connect", function () {
connect.server({
root: ["app"],
livereload: true,
port: 8034,
middleware: function (connect) {
return [connect().use("/bower", connect.static("bower"))];
}
});
});
If your project use AMD specification.
You can use gulp-edp bundle the modules.
set module info at module.conf
{
"baseUrl": "src",
"paths": {},
"packages": [
{
"name": "etpl",
"location": "../bower_components/etpl/3.0.1/src",
"main": "main"
},
{
"name": "jquery",
"location": "../bower_components/jquery/1.9.1/src",
"main": "jquery.min"
}
],
"combine": {
"app": true
}
}
gulpfile.js
var gulp = require('gulp');
var edp = require('gulp-edp');
gulp.src(
[
'src/**/*.js'
'bower_components/**/*.js',
'!bower_components/**/{demo,demo/**}',
'!bower_components/**/{test,test/**}'
]
)
.pipe(edp({
getProcessors: function () {
var moduleProcessor = new this.ModuleCompiler();
return [moduleProcessor];
}
}))
.pipe(gulp.dest('dist'));
See EDP wiki for more features.

Resources