使用 Webpack1.x 搭建 (MultiPage Application,MPA) 基础框架

初始化项目

webpack官方文档:https://www.webpackjs.com/con...
github项目地址:https://github.com/Zhanghongw...

项目搭建简单记录一下命令,网上有很多文章不多做介绍。
希望可以提供一个基础的架构。

持续更新........

执行命令

// 全局安装 webapck、webpack-cli, 之前安装过忽略此步骤

npm install webpack -g 

npm install webpack-cli -g

初始化 npm

npm init

项目目录结构

+dist
+src
++assets
+++images
++common
++page
++view

安装相关依赖,注意版本

npm install xxx@版本号 --save-dev
{
    "css-loader": "^2.1.1",
    "extract-text-webpack-plugin": "^1.0.1",
    "html-loader": "^0.4.5",
    "html-webpack-plugin": "^2.28.0",
    "style-loader": "^0.23.1",
    "url-loader": "^0.5.8",
    "webpack": "^1.15.0",
    "webpack-dev-server": "^1.16.5"
  }

webpack.config.js 配置文件

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

// 获取html-webpack-plugin参数的方法 
var getHtmlConfig = function(name){
  return {
      template    : './src/view/' + name + '.html',
      filename    : 'view/' + name + '.html',
      inject      : true,
      hash        : true,
      chunks      : ['common', name]
  };
};

var config = {
  entry: {
    'common':['./src/common/index.js'],
    'index':['./src/page/index/index.js'],
    'home':['./src/page/home/home.js']
  },
  output: {
    path: path.resolve(__dirname, "dist"),
    publicPath: "/dist",
    filename: 'js/[name].js'
  },
  module: {
    loaders: [

      // 处理 css
      { test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader","css-loader") },

      // 处理图片
      { test: /\.(gif|png|jpg|jpeg)\??.*$/, loader: 'url-loader?limit=100&name=resoure/[name].[ext]' }

    ]
  },
  plugins: [

    new webpack.optimize.CommonsChunkPlugin({
      // 公共模块提取
        name : 'common',
        filename : 'js/base.js'
    }),

    // 把css单独打包到文件里
    new ExtractTextPlugin("css/[name].css"),

    // html 模板处理
    new HtmlWebpackPlugin(getHtmlConfig('index')),
    new HtmlWebpackPlugin(getHtmlConfig('home'))
  ]
};

module.exports = config;

相关推荐