include scss in angular styleUrls

In ng2+, we can include css in the styleUrls on the component level to separate styling into file. In one of our recent project, we have a bunch of scss files to migrate, so we would like to include scss file to avoid major rewrite. We also have some global scss files which will be bundled by webpack withExtractTextPlugin  .

So we basically need 2 rules for scss:

 {
        test: /(main|index).scss$/,
        loader: ExtractTextPlugin.extract({
          fallbackLoader: "style-loader",
          loader: "css-loader!sass-loader",
        }),
      },
      {
        test: /\.scss$/,
        loader: ["raw-loader", "sass-loader",
          {
            loader: 'sass-resources-loader',
            options: {
              resources: ['./styles/global/_common.scss', './styles/global/_mixins.scss']
            },
          }
        ],
        // main scss will be handled by css/sass loader then ExtractTextPlugin then to the bundle css file.
        exclude: [helpers.root('styles/main.scss'), helpers.root('node_modules/header-footer/styles/index.scss')]
      },

If we use css-loader rather than raw loader for other scss files, then we get error message: Error: Uncaught (in promise): Expected 'styles' to be an array of strings..

The sass-resources-loader loader is helpful because it would make the shared commons/mixins available for all components so that we do not have to import them in each component to make the scss compilable.

disable the macos auto update notification

The auto update notification is pretty annoying since it popup everyday, and you need several clicks to make it disappear.

xmac-update-automatic

change from UI

I tried to disable it from System Preference -> App Store -> uncheck Automatically check for update. it does not that the checkbox keep checked after i reopen the system preference panel.

enable-or-disable-auto-apps-update-on-mac

Solution

Have to do it from command line via sudo.

	sudo ​softwareupdate --schedule off
	sudo defaults write /Library/Preferences/com.apple.SoftwareUpdate AutomaticCheckEnabled -bool FALSE

You can view the status by running
sudo defaults read /Library/Preferences/com.apple.SoftwareUpdate

React Native on a machine 8081 occupied

Today, as i was setting up a basic React native app on my company’s laptop, I cannot run the RN packager server which is default to port 8081​. I ran the lsof -i :8081 but get nothing. Turns out I have to run it with sudo because the app that uses this port is the Corporate Mcafee.

Obviously i do not want to uninstall Mcafee from the corporate laptop, I have to find a work around.

First thing to do is to run the packager server in a different port:

react-native start --port 8088

And now the packager server is up and running. However when i run react-native run-android , it still tells me JS server not recognized , so to get rid of this msg, i have to change some source code in the node module. The logic is in node_modules/react-native/local-cli/util/isPackagerRunning.js, and we just need to change the port in the fetch function from 8081 to the 8088 that we use above.

Now the android app should be able to be installed in the virtual device and run. However we still could not leverage the live reload capability of RN because if we double click r to reload, we get a red screen saying cannot connect to 10.0.2.2:8081. This is because when we use Genymotion virtual device, the code in node_modules/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/AndroidInfoHelpers.java will return that url. So we need to cmd+M in the emulator, Go to Dev Settings → Debug server host for device, enter ‘localhost:8081’. 

This is to overwrite the emulator’s debug server.(NOTE: if you are connecting your REAL android device, you do not have to change the above host).  Now we have the last step which is to forward the request in our local VD’s 8088 port to our machine’s 8088 port which runs the packager server by doing:

adb reverse tcp:8088 tcp:8088

The first part is VD and 2nd one is for the hosting machine. More about adb reverse. (Note: even for the VD, try to avoid using 8081. It would work for normal development/reload, but will not work with chrome remote debugging which still forwards the http request for index.android.bundle  to the host’s 8081 which is used by Mcafee.)

Now you should be able to change your index.android.js and hit r twice or cmd+M -> Reload to reload the VD.

webpack custom plugin

Recently we work with a platform which need to use webpack to build some ng2/4 assets and also some custom steps to pull data from a headless cms(via gulp) and eventually render components. One problem here is we cannot do live reload/recompile that every time we make some change we have to run the npm command again to compile the resources.

To solve the issue, i decided to write a custom webpack plugin to make browser-sync and webpack work together.

The basic flow is 1. run webpack in watch mode so every time a resouce(ts/css/html) changes, webpack auto re-compile, 2. serve the resources via browser-sync, here browserSync just serve as a mini express server and provide browser reload capability. 3. a webpack plugin to start the browser-sync server and register the reload event when webpack compilation is done.

Plugin

The webpack api is pretty straightforward, it exposes a compile object from the plugin’s apply function. It represents the fully configured Webpack environment. This object is built once upon starting Webpack, and is configured with all operational settings including options, loaders, and plugins. When applying a plugin to the Webpack environment, the plugin will receive a reference to this compiler. Use the compiler to access the main Webpack environment.

const browserSync = require('browser-sync');

function WebpackAndromedaPlugin(options) {
  console.log(`WebpackAndromedaPlugin options: ${JSON.stringify(options, null, 2)}`);

  let browserSyncConfig = require('./lib/dev-server').getBrowserSyncConfig(options);
  browserSyncConfig.server.middleware.push(require('./lib/dev-server').makeServeOnDemandMiddleware(options));
  browserSync.init(browserSyncConfig);
}

WebpackAndromedaPlugin.prototype.apply = (compiler) => {

  compiler.plugin("compile", function (params) {
    console.log('--->>> andromeda started compiling');
  });

  compiler.plugin('after-emit', (_compilation, callback) => {
    console.log('--->>> files prepared');
    browserSync.reload();
    callback();
  });
}

as we can see above, we can register our callbacks with compiler.pulgin(), where webpack exposes different stages for us to interact.

Another important object is compilation, which  represents a single build of versioned assets. While running Webpack development middleware, a new compilation will be created each time a file change is detected, thus generating a new set of compiled assets. A compilation surfaces information about the present state of module resources, compiled assets, changed files, and watched dependencies. The compilation also provides many callback points at which a plugin may choose to perform custom actions.

For example, all the generated files will be in compilation.assets object.

webpack-dev-middleware

The webpack-dev-middleware is a nice little express middleware that serves the files emitted from webpack over a connect server. One good feature it has is serving files from memory since it uses a in memory file system, which exposes some simple methods to read/write/check-existence in its MemoryFileSystem.js.  The webpack-dev-middleware also exposes some hooks like close/waitUntilValid etc, unfortunately the callback that waitUntilValid registers will only be called once according to the compileDone function here. Anyway, it is still an efficient tool to serve webpack resources and very easy to integrate with the webpack nodejs APIs:

~function() {
  const options = require('./config');
  let  webpackMiddleware = require("webpack-dev-middleware");

  let webpack = require('webpack');
  let browserSyncConfig = getBrowserSyncConfig(options);
  browserSyncConfig.server.middleware.push(makeServeOnDemandMiddleware(options));
  const compiler = webpack(require('./webpack.dev'));
  compiler.plugin('done', ()=>browserSync.reload())
  let inMemoryServer = webpackMiddleware(compiler, {noInfo: true, publicPath:'/assets'});
  browserSyncConfig.server.middleware.push(inMemoryServer);
  browserSync.init(browserSyncConfig);
}();

 

webpack-dev-server

The webpack-dev-server is basically a wrapper over the above webpack-dev-middleware. it is good for simple resources serving since it does not expose much. I was trying to find a hook to it to intercept the resource it generates/serves but did not get a good solution. If you need more customization, it would be better to go with webpack-dev-middleware.

a very detailed webpack intro article