3

I am using angular 1.5 with express in a very old project. now I need to revamp it (not rebuild).

I was adding some webpack optimisations and transferring it to client side rendering angular application and separating server code with client code.

My end goal is - to make a complete workflow using webpack 2 and angular 1.5, using ES6,6 features with most up to date code standards.

I want to use webpack 2 features like code splitting and tree shaking so that I can load all the modules on demand.

for this I created a webpack configuration. it works fine if I remove {modules: false} from .babelrc but adding this is essential for tree shaking.

my issue is, This is pretty much everything I need to do for implementing tree-shaking. but even after all this, my app.hash.js file after build contain all angular and lodash code. Instead it should be only code for module in case of angular and only map in case of lodash

this is my app index

import { module } from 'angular';
import { map } from 'lodash';

import '../style/app.css';

let app = () => {
  return {
    template: require('./app.html'),
    controller: 'AppCtrl',
    controllerAs: 'app'
  }
};

class AppCtrl {
  constructor() {
    this.appName = 'Fishry';

    const obj = {
      a: 'abc',
      d: 'efg'
    }
    _.map(obj, (value, key) => {
      console.log(value, key)
    })
  }
}

const MODULE_NAME = 'app';

module(MODULE_NAME, []).directive('app', app).controller('AppCtrl', AppCtrl);

export default MODULE_NAME;

this is my webpack conf

'use strict';

var webpack = require('webpack');
var autoprefixer = require('autoprefixer');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var ProgressBarPlugin = require('progress-bar-webpack-plugin');
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
var CompressionPlugin = require("compression-webpack-plugin");
var pkg = require('./package.json');

/**
 * Env
 * Get npm lifecycle event to identify the environment
 */
var ENV = process.env.npm_lifecycle_event;
var isTest = ENV === 'test' || ENV === 'test-watch';
var isProd = ENV === 'build';

module.exports = function makeWebpackConfig() {
  /**
   * This is the object where all configuration gets set
   */
  var config = {};

  /**
   * Should be an empty object if it's generating a test build
   * Karma will set this when it's a test build
   */
  config.entry = isTest ? void 0 : {
    app: './src/app/app.js',
    // vendor: ['angular', 'lodash'],
  };

  /**
   * Should be an empty object if it's generating a test build
   * Karma will handle setting it up for you when it's a test build
   */
  config.output = isTest ? {} : {
    // Absolute output directory
    path: __dirname + '/dist',

    // Output path from the view of the page
    // Uses webpack-dev-server in development
    publicPath: isProd ? '/' : 'http://localhost:8080/',

    // Filename for entry points
    // Only adds hash in build mode
    filename: isProd ? '[name].[hash].js' : '[name].bundle.js',

    // Filename for non-entry points
    // Only adds hash in build mode
    chunkFilename: isProd ? '[name].[hash].js' : '[name].bundle.js'
  };

  /**
   * Devtool
   * Reference: http://webpack.github.io/docs/configuration.html#devtool
   * Type of sourcemap to use per build type
   */
  if (isTest) {
    config.devtool = 'inline-source-map';
  } else if (isProd) {
    config.devtool = 'source-map';
  } else {
    config.devtool = 'source-map';
  }

  /**
   * Loaders
   * Reference: http://webpack.github.io/docs/configuration.html#module-loaders
   * List: http://webpack.github.io/docs/list-of-loaders.html
   * This handles most of the magic responsible for converting modules
   */

  // Initialize module
  config.module = {
    rules: [
      { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
      {
        test: /\.css$/,
        loader: isTest ? 'null-loader' : ExtractTextPlugin.extract({
          fallbackLoader: 'style-loader',
          loader: [
            {loader: 'css-loader', query: {sourceMap: true}},
            {loader: 'postcss-loader'}
          ],
        })
      },
      { test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/, loader: 'file-loader' },
      { test: /\.html$/, loader: 'raw-loader' }
    ]
  };

  // ISTANBUL LOADER
  // https://github.com/deepsweet/istanbul-instrumenter-loader
  // Instrument JS files with istanbul-lib-instrument for subsequent code coverage reporting
  // Skips node_modules and files that end with .spec.js
  if (isTest) {
    config.module.rules.push({
      enforce: 'pre',
      test: /\.js$/,
      exclude: [
        /node_modules/,
        /\.spec\.js$/
      ],
      loader: 'istanbul-instrumenter-loader',
      query: {
        esModules: true
      }
    })
  }

  config.plugins = [
    new webpack.LoaderOptionsPlugin({
      test: /\.scss$/i,
      options: {
        postcss: {
          plugins: [autoprefixer]
        }
      }
    }),
    new ProgressBarPlugin()
  ];

  if (!isTest) {
    config.plugins.push(
      new HtmlWebpackPlugin({
        template: './src/public/index.html',
        inject: 'body'
      }),
      new ExtractTextPlugin({filename: 'css/[name].css', disable: !isProd, allChunks: true})
    )
  }

  // Add build specific plugins
  if (isProd) {
    config.plugins.push(
      new webpack.NoEmitOnErrorsPlugin(),
      // new BundleAnalyzerPlugin({
      //   analyzerMode: 'static'
      // }),
      // new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.bundle.js' }),
      new webpack.optimize.UglifyJsPlugin(),
      new CompressionPlugin({
        asset: "[path].gz[query]",
        algorithm: "gzip",
        test: /\.(js|html)$/,
        threshold: 10240,
        minRatio: 0.8
      }),
      new CopyWebpackPlugin([{
        from: __dirname + '/src/public'
      }]),

      new webpack.BannerPlugin('Fishry SDK ' + pkg.version + ' - copyrights reserved at Bramerz (PVT) ltd')
    )
  }

  /**
   * Dev server configuration
   * Reference: http://webpack.github.io/docs/configuration.html#devserver
   * Reference: http://webpack.github.io/docs/webpack-dev-server.html
   */
  config.devServer = {
    contentBase: './src/public',
    stats: 'minimal'
  };

  return config;
}();

and this is by .babelrc file

{
  "presets": [
    ["es2015", {modules: false}],
    "stage-0"
  ],
  "plugins": [
    "angularjs-annotate",
    "transform-runtime"
  ]
}
Usman Tahir
  • 2,513
  • 4
  • 24
  • 38

0 Answers0