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

时间:2016-01-05 09:28:15

标签: javascript html cordova webpack webpack-dev-server

我有一个app.bundle.js(基本上是主应用程序包)和两个cordova捆绑包:iosCordova.bundle.js和androidCordova.bundle.js。我只根据用户是登录ios还是android登录src中的一个。我在生成的文件夹(名为_dist)中包含所有捆绑包,css,png和除index.html之外的所有内容。我不能把index.html使用htmlWebpackPlugin放在这个文件夹中,因为否则会有一个自动脚本src到两个cordova捆绑(这是我想要避免的)。我的问题是构建项目:当我运行构建时,它在_dist中查找index.html,结果为404. FYI当我运行“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>

1 个答案:

答案 0 :(得分:1)

所以答案是:

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