Angular 1.5 - 使用webpack& babel 6

时间:2017-05-17 10:22:12

标签: angularjs webpack babeljs code-splitting tree-shaking

我在一个非常古老的项目中使用angular 1.5 with express。现在我需要改进它(不是重建)。

我正在添加一些webpack优化并将其转移到客户端,呈现角度应用程序并使用客户端代码分离服务器代码。

我的最终目标是 - 使用带有最新代码标准的ES6,6功能,使用webpack 2和angular 1.5制作完整的工作流程。

我想使用webpack 2功能,例如代码拆分和树摇动,以便我可以按需加载所有模块。

为此我创建了一个webpack配置。如果我从{modules: false}删除.babelrc,它可以正常工作,但添加这对于树是必不可少的 晃动。

我的问题是,这几乎是我实施树摇动所需要做的一切。但即使在这之后,构建后的app.hash.js文件也包含所有angularlodash代码。 相反,在角度的情况下,module的代码应该只有 lodash

时只有map的代码

这是我的应用索引

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;

这是我的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;
}();

这是.babelrc文件

{
  "presets": [
    ["es2015", {modules: false}],
    "stage-0"
  ],
  "plugins": [
    "angularjs-annotate",
    "transform-runtime"
  ]
}

0 个答案:

没有答案