前端工程之多页面webpack打包模板

2017-12-27  本文已影响0人  leyou319

如何配置一个多页应用webpack工程化模板?

webpack的四个核心概念:

  1. entry
  1. output
  1. loader
  1. plugin

项目目录

|--src
|  |--images             图片
|  |--sass               样式
|     |-- reset.scss
|     |-- index.scss
|     |-- list.scss
|  |--includes           html公共模板
|     |-- head.pug
|     |-- foot.pug
|  |--js                 js逻辑相关
|     |--util            js工具函数
|        |-- common.js 
|     |-- index.js 
|     |-- list.js
|  |--index.pug  
|  |--list.pug  
|-- webpack.config.js    webpack打包配置
|-- package.json         项目依赖信息
|-- README.md            项目说明
|-- .gitignore           git忽略配置

webpack配置

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

// 环境变量配置,dev / online
var WEBPACK_ENV = process.env.WEBPACK_ENV || 'dev';

var config = {
    entry: {
        'index': './src/js/index.js',
        'list': './src/js/list.js',
        'about': './src/js/about.js'
    },
    output: {
        path: __dirname + '/dist/',
        publicPath: 'dev' === WEBPACK_ENV ? '/dist/' : '//leyou319.github.io/multipage_webpack/dist/',
        filename: 'js/[name].js'
    },
    module: {
        rules: [
            {
                test: /\.scss$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: ['css-loader?sourceMap=true', 'sass-loader?sourceMap=true']
                })
            },
            {
                test: /\.(png|jpg|gif)$/,
                use: 'url-loader?limit=8192&name=images/[name].[ext]?[hash:6]'
            },
            {
                test: /\.pug$/,
                use: ['html-loader','pug-html-loader?pretty=true']
            }
        ]
    },
    plugins: [
        new ExtractTextPlugin('css/[name].css'),
        new webpack.optimize.CommonsChunkPlugin({
            name : 'common',
            filename : 'js/common.js'
        }),
    ],
    externals : {
        'jquery' : 'window.jQuery'
    },
    devServer: {
        inline: true,
        proxy: {
            '/ajaxload': {
                target: 'http://www.gitchic.com',
                secure: false,
                changeOrigin: true
            }
        }
    }
}

Object.keys(config.entry).forEach(function(page){
    config.plugins.push( new HtmlWebpackPlugin({
        template: './src/'+ page +'.pug',
        filename: page+'.html',
        inject: true,
        hash: true,
        chunks: ['common', page]
    }) );
});

if('dev' === WEBPACK_ENV){
    config.devtool = 'inline-source-map';
}

module.exports = config;

package配置

"scripts": {
    "dev": "webpack-dev-server",
    "build": "set WEBPACK_ENV=online && webpack -p"
 }

命令行相关

1. 开发环境
npm run dev

2. 生产打包
npm run build

项目预览

项目地址
线上预览

上一篇 下一篇

猜你喜欢

热点阅读