请使用firefox,chrome等最新浏览器浏览本站。

前端开发规范-react/react-router/redux/webpack/es6开发配置

js+jquery 阿豹 1524次浏览 0个评论 扫描二维码

项目地址: https://github.com/fangyongbao/react-router-redux-webpack

这里的webpack配置是针对多页面开发, 单页面中进行路由跳转,这里需要5个相关配置文件:

package.json 定义项目依赖模块 以及 定义开启服务器和打包命令
helpers.js 获取入口文件和html文件
webpack.base.config.js 定义webpack基础配置
webpack.dev.config.js 定义webpack开发配置
webpack.prod.config.js 定义webpack生产配置

改项目中包含了:

路由跳转
数据请求模块封装
webview与js交互模块封装
配置文件分离
自动打包多个html文件
以一个简单的例子实现 dispatch->action->reducer->state->view流程
定义共用sass文件
提取css
css自动添加浏览器前缀
上线包添加静态资源版本号
上线包css/js压缩
定义第三方字体库

使用方式:

1.npm install webpack-dev-server -g 全局安装服务器
2.到package.json所在目录执行npm install 安装依赖模块
3.npm run start 开启服务器(包含热更新)
4.浏览器访问localhost:80
5.npm run build打包

webpack相关配置文件

package.json文件:

    {
  "name": "pass",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "webpack-dev-server --inline --hot --port 3000 --progress --profile --colors --watch --display-error-details  --display-cached  --config ./webpack.dev.config.js",
    "build": "webpack --progress --profile --colors --display-error-details --display-cached --bail   --config ./webpack.prod.config.js"
  },
  "author": "maicon",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.0.0",
    "babel-loader": "^6.0.0",
    "babel-plugin-transform-runtime": "^6.0.0",
    "babel-preset-es2015": "^6.0.0",
    "babel-preset-react": "^6.0.0",
    "copy-webpack-plugin": "^3.0.1",
    "css-loader": "^0.23.0",
    "express": "^4.13.3",
    "extract-text-webpack-plugin": "^1.0.1",
    "file-loader": "^0.9.0",
    "glob": "^7.0.6",
    "html-webpack-plugin": "^2.8.1",
    "json-loader": "^0.5.4",
    "node-sass": "^3.8.0",
    "sass-loader": "^4.0.0",
    "style-loader": "^0.13.1",
    "url-loader": "^0.5.7",
    "webpack": "^1.12.2"
  },
  "dependencies": {
    "babel-polyfill": "^6.13.0",
    "es6-promise": "^3.2.1",
    "jquery": "^3.1.0",
    "md5": "^2.2.1",
    "react": "^15.3.0",
    "react-dom": "^15.3.0",
    "react-redux": "^4.4.5",
    "react-router": "^2.7.0",
    "redux": "^3.5.2",
    "redux-thunk": "^2.1.0"
  }
}

helpers.js文件

var glob = require('glob');
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');

function getHtmlPlugin() {
    var buildPath = '';
    var plugins = [];
    glob.sync('./*.html').forEach(function (name) {
        //[^/]不匹配这个集合中的任何一个字符 
        var n = name.match(/([^/]+)\.html/)[1];
        plugins.push(
            new HtmlWebpackPlugin({
                filename:buildPath+n+'.html',
                template:name,
                inject:false
            })
        )
    });
    return plugins;
}

function getEntry() {
    var entry = {};
    glob.sync('./entry/*.js').forEach(function (name) {
        console.log(name);
        //[^/]不匹配这个集合中的任何一个字符 
        var n = name.match(/([^/]+)\.js/)[1];
        entry[n] = name;
    });
    return entry;
};

exports.getHtmlPlugin = getHtmlPlugin;
exports.getEntry = getEntry;

webpack.base.config.js文件

var path = require('path');
var webpack = require('webpack');
var helpers = require('./helpers');

module.exports = {
    //入口文件
    entry: helpers.getEntry(),

    //输出文件
    output: {
        path: path.join(__dirname, '/dist'),
        //热更新资源存放目录
        //publicPath:'/',
        filename: 'js/[name].js',
    },

    resolve: {
        //定义模块缩写名称
        alias: {
            'common.scss':path.join(__dirname,'/src/assets/scss/common.scss')
        },
        //resolve 指定可以被 import 的文件后缀
        extensions: ['', '.js', '.css', '.scss']
    },
    
    module: {
        //加载器配置
        loaders: [
            {
                test:/\.js?$/,
                loader:'babel-loader',
                exclude: /node_modules/,
                query:{
                    presets:['es2015','react']
                }
            },
            {
                test: /\.scss/,
                loader: 'style-loader!css-loader!sass-loader'
            }, 
            {
                test: /\.css$/,
                loader: 'style-loader!css-loader'
            },
            { 
                test: /\.(jpe?g|png|gif|svg)$/i,
                loader: 'url-loader?limit=1000&name=images/[name].[ext]',
                query:{}
            },
            {
                test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
                loader: 'url-loader',
                query: {
                  limit: 10000,
                  name: 'fonts/[name].[ext]'
                }
            }
        ]      
    },
    //插件项
    plugins: [
       
    ]
}

webpack.dev.config.js文件

  var path = require('path');
var webpack = require('webpack');
var helpers = require('./helpers');
var commonWebpack = require('./webpack.base.config');
//var CopyWebpackPlugin = require('copy-webpack-plugin');

const METADATA = {
    host: '.'
};

module.exports = Object.assign({}, commonWebpack, {
    //供html使用的变量
    metadata: METADATA,
    //开发环境设定独立的插件
    plugins: [
        //commonsPlugin 可以用于分析模块的共用代码, 单独打一个包出来
        new webpack.optimize.CommonsChunkPlugin('js/common.js'),
        //代码热替换
        new webpack.HotModuleReplacementPlugin(),
        //将图片拷贝到指定位置
        // new CopyWebpackPlugin([{
        //     from: 'src/assets/images',
        //     to: 'images'
        // }]),
        //React 官方提供的代码是已经合并的, 这个是 Webpack 不推荐的用法,
        //在合并话的代码上进行定制有点麻烦, Webpack 提供了设置环境变量来优化代码的方案:
        new webpack.DefinePlugin({
            //配置组件中使用的变量,组件中可以直接使用{metadata.host}
            metadata:JSON.stringify(METADATA),
            "process.env": {
                NODE_ENV: JSON.stringify("production")
            }
        })
        //concat进行数组合并
    ].concat(helpers.getHtmlPlugin())
});  

webpack.prod.config.js文件

var path = require('path');
var webpack = require('webpack');
var helpers = require('./helpers');
var commonWebpack = require('./webpack.base.config');
var ExtractTextPlugin = require('extract-text-webpack-plugin')
//var CopyWebpackPlugin = require('copy-webpack-plugin');

const METADATA = {
    host: '.'
};

module.exports = Object.assign({}, commonWebpack, {
    //供html使用的变量
    metadata: METADATA,
    plugins: [
        //commonsPlugin 可以用于分析模块的共用代码, 单独打一个包出来
        new webpack.optimize.CommonsChunkPlugin('js/common.js'),
        new webpack.HotModuleReplacementPlugin(),
        //将图片拷贝到指定位置
        // new CopyWebpackPlugin([{
        //     from: 'src/assets/images',
        //     to: 'images'
        // }]),
        // 提取css为单文件
        //new ExtractTextPlugin("css/[name].css"),
        //压缩js代码
        new webpack.optimize.UglifyJsPlugin({
            output: {
                comments: false
            },
            compress: {
                warnings: false
            }
        }),
        //React 官方提供的代码是已经合并的, 这个是 Webpack 不推荐的用法,
        //在合并话的代码上进行定制有点麻烦, Webpack 提供了设置环境变量来优化代码的方案:
        new webpack.DefinePlugin({
            //配置组件中使用的变量,组件中可以直接使用{metadata.host}
            metadata:JSON.stringify(METADATA),
            "process.env": {
                NODE_ENV: JSON.stringify("production")
            }
        })
        //concat进行数组合并
    ].concat(helpers.getHtmlPlugin())
});

喜欢 (15)or分享 (0)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到