This website requires JavaScript.

webpack多页面配置

2018.04.10 10:02字数 2682阅读 408喜欢 0评论 0

为什么需要使用 webpack 构建多页应用呢?因为某些项目使用 SPA 不太合适(大多是 SEO 的原因),或者您在做项目时有其他的需求。
对我自己而言,因为公司app的内存管理机制缺陷,所以使用多页面自动清理机制。

let  webpack = require('webpack');
let  path = require('path');
let  glob = require('glob');
let  ExtractTextPlugin = require("extract-text-webpack-plugin");
let  CleanWebpackPlugin = require('clean-webpack-plugin');
let  HtmlWebpackPlugin = require('html-webpack-plugin');

let  entries = getEntry('./src/pages/*.js');
let  name = process.argv.slice(5);
let  config = {
    cache: true,
    entry: entries,
    output: {
        path: path.join(__dirname, '../web'),
        publicPath: "",
        filename: name == 'dev' ? 'static/js/[name].js' : 'static/js/[name]_[chunkhash:10].js'
    },
    resolve: {
        alias: {
            vue: 'vue/dist/vue',
            utils: __dirname + '/src/lib/utils.js',
            components: __dirname + '/src/components'
        }
    },
    module: {
        loaders: [
            { test: /\.vue$/, loader: 'vue' },
            { test: /\.js$/, loader: 'babel', exclude: /node_modules/ },
            { test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader") },
            { test: /\.scss$/, loader: "style!css!sass" },
            { test: /\.less$/, loader: "style!css!less" },
            {
                test: /\.(gif|jpg|png|woff|svg|eot|ttf)\??.*$/,
                loader: 'url-loader?limit=999999'
            }
        ]
    },
    plugins: [
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        }),
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'manifest'
        }),
        new ExtractTextPlugin("assets/css/styles.css"),
        new CleanWebpackPlugin(['web'], {
         root: __dirname,
         verbose: true,
         dry: false,
         exclude: ['images', 'css', 'robots.txt', 'favicon.ico']
         })
    ]
}

function getEntry(filepath) {
    let  files = glob.sync(filepath);
    let  entries = {};
    files.forEach(function(item) {
        let  pathname = path.basename(item, path.extname(item))
        entries[pathname] = item;
    });
    return entries;
}
module.exports = config;

let  pages = getEntry('./src/views/*.html');
for (let  pathname in pages) {
    let  conf = {
        filename: pathname + '.html',
        template: pages[pathname],
        minify: {
            removeComments: true,
            collapseWhitespace: false
        },
        //hash: true,
        inject: true,
        chunks: [pathname, "vendor", "manifest"]
    };
    module.exports.plugins.push(new HtmlWebpackPlugin(conf));
}