如何从webpack-dev-server为临时index.html订购静态资产?

时间:2016-09-12 23:09:41

标签: webpack webpack-dev-server

我一直关注有关webpack的Angular 2文档。我正在尝试使用webpack-dev-server来帮助测试我的应用程序。入口点包括polyfills,vendor和app。

当我尝试运行开发服务器时,文件会被命名为polyfills,app和app。

当它们在index.html模板中呈现时,有没有办法明确地对它们进行排序?



var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var helpers = require('./helpers');

module.exports = {
    cache: false,
    debug: true,

    entry: {
        'polyfills': './src/polyfills.ts',
        'vendor': './src/vendor.ts',
        'vip-app': './src/main.ts'
    },

    resolve: {
        extensions: ['', '.js', '.ts'],
    },

    module: {
        loaders: [
            {
                test: /\.ts$/,
                loaders: ['ts', 'angular2-template-loader']
            },
            {
                test: /\.html$/,
                loader: 'html'
            },
            {
                test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
                loader: 'file?name=assets/[name].[hash].[ext]'
            },
            {
                test: /\.css$/,
                loaders: [ExtractTextPlugin.extract('style', 'css-loader'), 'to-string', 'css']
            }
        ]
    },

    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            name: ['vendor', 'polyfills']
        }),

        new HtmlWebpackPlugin({
            template: 'index.html'
        })
    ]
};






<!DOCTYPE html>
<html>
<head>
    <base href="/">
    <title>Angular With Webpack</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
<link href="http://localhost:8080/vip-app.css" rel="stylesheet"></head>
<body>
    <vip-app-base-local-dev>Loading...</vip-app-base-local-dev>
    <script type="text/javascript" src="http://localhost:8080/polyfills.js"></script>
    <script type="text/javascript" src="http://localhost:8080/vip-app.js"></script>
    <script type="text/javascript" src="http://localhost:8080/vendor.js"></script></body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

您可以使用 HtmlWebpackPlugin 中的chunkSortMode选项来获取它。

  

chunksSortMode:允许控制之前应如何排序块   它们包含在html中。允许值:&#39;无&#39; | &#39;自动&#39; |   &#39;依赖性&#39; | {function} - 默认:&#39;自动&#39;

例如

1)此选项

chunksSortMode: 'none'

将按字母顺序对您的块进行排序

2)选项

chunksSortMode: 'dependency'

将根据彼此的依赖关系对您的块进行排序。

3)你也可以编写自定义函数,如:

function sortChunk(packages) {
  return function sort(a, b) {
     if (packages.indexOf(a.names[0]) > packages.indexOf(b.names[0])) {
        return 1;
      }
      if (packages.indexOf(a.names[0]) < packages.indexOf(b.names[0])) {
        return -1;
      }
      return 0;
  }
}

并像

一样使用它
new HtmlWebpackPlugin({
   template: 'index.html',
   chunksSortMode: sortChunk(['vip-app', 'vendor', 'polyfills' ])
})

达到理想的秩序

vip-app' => 'vendor' ==> 'polyfills'