如何在 webpack 中有条件地使用 bundle

How to conditionally use a bundle in webpack

我有一个 app.bundle.js(基本上是主应用程序包)和两个 cordova 包:iosCordova.bundle.js 和 androidCordova.bundle.js。我只根据用户登录的是 ios 还是 android 来编写其中之一的 src 脚本。我在生成的文件夹(名为 _dist)中拥有所有捆绑包、css、png 和除 index.html 之外的所有内容。我不能将 index.html using htmlWebpackPlugin 放在这个文件夹中,否则会有一个自动脚本 src 到两个 cordova 包(这是我想避免的)。我的问题是构建项目:当我 运行 构建它时,它正在 _dist 中寻找 index.html,结果是 404。仅供参考,当我 运行 "npm run dev" 但是它知道它应该在主文件夹中寻找 index.html 而 app.bundle.css 和 app.css 应该在 _dist.

我的webpack.config:

    config.entry = {
        app: './app.js',
        iosCordova: ['./static/wrapper/js/ios/cordova_all.min.js'],
        androidCordova: ['./static/wrapper/js/android/cordova_all.min.js']
    };

    config.output = {
        path: __dirname + '/_dist',

        publicPath: 'localhost:8080/',

        filename: '[name].bundle.js',

        chunkFilename: '[name].bundle.js'
    };

    config.module = {
        noParse: /node_modules\/html2canvas/,
        preLoaders: [],
        loaders: [
            {

                test: /\.js$/,              
                loader: 'babel?optional[]=runtime',
                presets: ['es2015'],
                exclude: [
                    /node_modules/,
                    /cordova_all/
                ]
            },
            {
                test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/,
                loader: 'file?name=[name].[ext]'
            }, {
                test: /\.html$/,
                loader: "ngtemplate?relativeTo=" + __dirname + "!raw"
            }]
    };
    var cssLoader = {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract('style', 'css?sourceMap!postcss', 'scss', 'sass')
    };

    config.module.loaders.push(cssLoader);
    config.devServer = {
        stats: {
            modules: false,
            cached: false,
            colors: true,
            chunk: false
        }
    };

    //config.resolve = {
    //  alias: {
    //      moment: "node_modules/moment/min/moment.min.js"
    //      //"jquery-ui": "vendor/plugins/jquery-ui.min.js"
    //  }
    //};

    return config;
};

index.html:

<!DOCTYPE html>

...

<html>
<head>
    <script type="text/javascript">
        (function(){

            if (window.location.search.indexOf('cordova=') > -1) {
                var platform = /i(phone|pod|pad)/gi.test(navigator.appVersion) ? 'iosCordova.bundle.js' : 'androidCordova.bundle.js';

                var cordovaScript = document.createElement('script');
                cordovaScript.setAttribute('src',platform);
                document.head.appendChild(cordovaScript);
            }
        }());
    </script>

    <link href="app.css" rel="stylesheet">
</head>

...

<script src="app.bundle.js"></script>
</body>
</html>

所以答案是:

config.plugins.push(
    new HtmlWebpackPlugin({
        template: './index.html',
        inject: true,
        excludeChunks: ['app','iosCordova','androidCordova']
    })
);