react-webpack2-Complete Case __web

Source: Internet
Author: User
Tags md5 postcss
React-webpack 2-full configuration case

Source

Webpack Development Cross-domain problem solving
React16 + react-router4 + webpack development environment Build 1. Define some configuration constants first/webpack/config.js

    Introduce node.js path Module const PATH = require (' path ');

    Sass-loader Configuration Exports.sassloaderconfig = '? outputstyle=expanded ';
        Public file Exports.vendor = [' react ', ' react-dom ', ' react-redux ', ' react-router ',

    ' React-router-redux ', ' redux ', ' redux-thunk '];
            CSS code Auto-completion Configuration Exports.autoconfig = {browsers: [' IE >= 9 ', ' Ie_mob >= 10 ',
            ' FF >= ', ' Chrome >= ', ' Safari >= 7 ', ' Opera >= 23 ',
        ' iOS >= 7 ', ' Android >= 4.4 ', ' BB >= ', Cascade:true,

    Remove:true}; JS Compression Configuration Exports.uglifyjsconfig = {beautify:false,//No landscaping output compress: {warnings:
        False,//do not keep warning drop_debugger:true///Do not keep Debug statement drop_console:true//Do not keep console output information},           Mangle: {Skip these and do not change the name except: [' $super ', ' $ ', ' exports ', ' require ']}, Space_colon:false, com

    Ments:false//Do not keep comment}; Definition file path Note: File in the root directory under the Webpack folder under const Root_path = Path.resolve (__dirname, ' ...
    /'); Exports.defpath = {Root_path:root_path, APP_PATH:path.resolve (Root_path, ' APP '), Dev_path:path . Resolve (Root_path, ' Dev '), BUILD_PATH:path.resolve (Root_path, ' build '), TPL_PATH:path.resolve (Root_path , ' app/tpl.html '), ENTRY_PATH:path.resolve (Root_path, ' app/js/index.js '), ESLINT_PATH:path.resolve (root_
 PATH, './.eslintrc '), REQUEST_PATH:path.resolve (Root_path, ' App/js/utils/request ')}
2. Define application request configuration under different environment variables
    ' NPM install IP ' gets native IP to configure server
    const IP = require (' IP '). address ();

    Module.exports = {
        test: ' http://xxx.xxx ',
        development: ' http://' + IP + ': 3003 ',
        production: ' http:// Xxx.xxx '
    };
define a public configuration/webpack/base.js
    Const WEBPACK = require (' Webpack ');
    Const AUTOPREFIXER = require (' autoprefixer ');

    Const Htmlwebpackplugin = require (' Html-webpack-plugin '); Const CONFIG = require ('./config ');
    Introducing the configuration Const API = require ('./api ');
    Const DEFPATH = Config.defpath; Const APP_PATH = Defpath.app_path;
          SOURCE Directory module.exports = function () {return {Context:defPath.ROOT_PATH,//Set directory for execution Environment
             Resolve: {//Parsing module request options Modules: [App_path, ' Node_modules '
            /////////directory for locating modules extensions: ['. js ', '. json ', '. Jsx ', '. css ' ]//Use of extension}, cache:true,//Enable cache module: {//Common loader R Ules: [{enforce: ' pre ',//predecessor Execute Test:/\. (
     JS|JSX) $/, Include:app_path, loader: ' Eslint-loader ',              Options: {configFile:defPath.ESLINT_PATH//Specify Eslint configuration file path} }, {test:/\.
                (JS|JSX) $/, Include:app_path, loader: ' Babel-loader '},
                   {///to inject variable into application specific file, the application can use BaseURL Test:require.resolve (Defpath.request_path) directly. Loader: ' imports-loader?baseurl=> ' + json.stringify (api[Process.env.NODE_ENV | | ' Development ']}]}, plugins: [//Autoprefixer is POSTCSS -loader plug-in, you need to do the Autoprefixer plug-in configuration new Webpack.
                   Loaderoptionsplugin ({options: {context: '/', minimize:true,
             POSTCSS: [Autoprefixer (Config.autoconfig)]}},//Generate HTML according to template
            New Htmlwebpackplugin ({    Template:defPath.TPL_PATH, title: ' Hello World app ', FileName: ' index.html ',
                Inject: ' Body ', minify: {removecomments:true},
 Cache:false})]}}
webpack configuration/webpack.dev.config.js for the development environment
    Const Webpackmerge = require (' Webpack-merge ');
    Const WEBPACK = require (' Webpack ');
    Const Chunkmanifestplugin = require (' Chunk-manifest-webpack-plugin ');

    Const IP = require (' IP '). Address ();
    Const BASECONFIG = require ('./webpack/base ');
    Const CONFIG = require ('./webpack/config ');
    Const DEFPATH = Config.defpath;

    Const APP_PATH = Defpath.app_path; Use ' webpack-merge ' to merge the underlying configuration and new configuration Module.exports = Webpackmerge (Baseconfig (), {devtool: ' cheap-module-source-
                Map ',//Enhanced Browser Debugging entry: {//Portal app: [//Gegas load configuration ' React-hot-loader/patch ',
                ' webpack-dev-server/client?http://' + IP + ': 8090 ', ' webpack/hot/only-dev-server ',
            './app/js/index.js '], Vendor:config.vendor//Public files individually packaged}, output: {//Export Path:defPath.DEV_PATH,//All output file destination path//destination path of all output files filename: ' Js/bundle.js ',/ /output FileName Publicpath: '/',//must be written and consistent with Devserver's Publicpath chunkfilename: ' [name].chunk.js ' Block file naming}, module: {rules: [//config loader {test:/\. ( SCSS|SASS|CSS) $/, Include:app_path,//must match option use: [//2.x version instead of LO Aders, must add-loader ' Style-loader ', ' css-loader ', ' postcss-loader ', ' sass-loader ' + config.sassloade Rconfig]}, {test:/\. ( EOT|WOFF|WOFF2|TTF|SVG|PNG|JPE?G|GIF|MP4|WEBM) (\?\s*)? $/, Include:app_path, Loade R: ' Url-loader?limit=8192&name=imgs/[name]. [ext] '}]}, plugins: [///Hot module replaces the associated plugin new webpack. Hotmodulereplacementplugin (), New Webpack. Namedmodulesplugin (),//define environment variable new webpack.
        Defineplugin ({        ' Process.env.NODE_ENV ': json.stringify (' Development ')},/* Public modules packaged separately, corresponding
                Portal file Vendor, persistent cache configuration/new Webpack.optimize.CommonsChunkPlugin ({
                Names: [//Extract public module name ' Vendor ', ' manifest '//Manifest for separation Webpack runtime], FileName: ' js/[name].js ',//public module filename minchunks:infinity//Infinity means just creating a public component block that won't put any mod
            Ules packed in.
             }), new Chunkmanifestplugin ({//manifest extracted to a separate JSON file filename: ' Chunk-manifest.json ',
        Manifestvariable: ' webpackmanifest '/name of global variable, Webpack will use it to find manifest JSON object}] Devserver: {//Open server ContentBase:defPath.DEV_PATH, Publicpath: '/', historyapif
   Allback:true, Clientloglevel: ' None ', Host:ip, port:8090, Open:true,         Hot:true, Inline:true, compress:true, stats: {Colors:tru E, Errors:true, Warnings:true, Modules:false, chunks:f
 Alse}}})
production Environment Webpack configuration/webpack.prod.config.js
    Const Webpackmerge = require (' Webpack-merge ');
    Const WEBPACK = require (' Webpack ');
    Const Chunkmanifestplugin = require (' Chunk-manifest-webpack-plugin ');
    Const Extracttextplugin = require (' Extract-text-webpack-plugin ');

    Const Webpackmd5hash = require (' Webpack-md5-hash ');
    Const BASECONFIG = require ('./webpack/base ');
    Const CONFIG = require ('./webpack/config ');
    Const DEFPATH = Config.defpath;

    Const APP_PATH = Defpath.app_path; Module.exports = Webpackmerge (Baseconfig (), {entry: {App:defPath.ENTRY_PATH, Vendor:co Nfig.vendor}, Output: {Path:defPath.BUILD_PATH,//target path file for all output files Name: ' Js/bundle.js? [Chunkhash] ', Publicpath: ' http://xxx.xxx ',//modified to published address chunkfilename: ' Chunk.js? [Chunkhash] '}, module: {rules: [{test:/\. ( SCSS|SASS|CSS) $/, include:aPp_path, Use:ExtractTextPlugin.extract ({//CSS individually packaged, (2.x change very large) fallback:
                    ' Style-loader ', use: ' Css-loader!postcss-loader!sass-loader ' + config.sassloaderconfig }}, {test:/\. (EOT|WOFF|WOFF2|TTF|SVG|PNG|JPE?G|GIF|MP4|WEBM) (\?\s*) $/, Include:app_path, loader: ' url-loader?limit=8192&name=imgs/[name] . [ext]? [Hash] '}]}, plugins: [New Webpackmd5hash (),//replace Standard Webpack C Hunkhash new Webpack.
            Defineplugin ({' Process.env.NODE_ENV ': json.stringify (' production ')}),//JS compression New Webpack.optimize.UglifyJsPlugin (Config.uglifyjsconfig), new Webpack.optimize.CommonsChunkPlugi N ({names: [' Vendor ', ' manifest '], filename: ' js/[Name].js? [Chunkhash] ', minchunks:infinity}), new Chunkmanifestplugin ({fi
            Lename: ' Chunk-manifest.json ', manifestvariable: ' Webpackmanifest '}),//CSS Extraction New Extracttextplugin ({filename: ' css/styles.css?[
 Contenthash] ', Disable:false, Allchunks:true}]})
the corresponding Babel configuration/.BABELRC
    {
        "presets": [
            ["es2015", {
                "modules": false
            }],
            "stage-2",
            "react"
        ],
        "plugins": [
            "React-hot-loader/babel",
            "Transform-object-assign",
            "Transform-decorators-legacy"
        ],
        "env": {
            "development": {"plugins":
                [
                    "React-hot-loader/babel"
                ]
    }}}
List of important plug-in versions
{"
    webpack": "^2.2.1", "
    webpack-dev-server": "^2.4.1",
    "Webpack-md5-hash": "0.0.5",
    " Webpack-merge ":" ^4.0.0 ","
    chunk-manifest-webpack-plugin ":" ^1.0.0 ",
    " Extract-text-webpack-plugin ":" ^ 2.1.0 ",
    " Html-webpack-plugin ":" ^2.28.0 ",
    " React-hot-loader ":" ^3.0.0-beta.6 ",
}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.