webpack+react+ES6(原创+转载)

搭建项目过程:

Package.json

1.打开命令行工具 cmd

2.默认安装好nodejs以及全局安装webpack

3.在适当的地方新建目录

  mkdir webpack-react-es6

  cd webpack-react-es6

  npm init  回车

4.打开package.json文件

  {

  "name": "frame",                            //名称

  "version": "1.0.0",                         //版本

  "description": "",

  "dependencies": {},

  "devDependencies": {                        //所有需要安装的依赖

    "antd": "2.7.2",

    "babel-core": "^6.0.0",

    "babel-loader": "^6.2.4",

    "babel-plugin-import": "^1.1.1",

    "babel-polyfill": "^6.7.4",

    "babel-preset-es2015": "^6.3.13",

    "babel-preset-es2015-ie": "^6.6.2",

    "babel-preset-react": "^6.5.0",

    "babel-preset-react-hmre": "^1.1.1",

    "babel-preset-stage-0": "^6.5.0",

    "classnames": "^2.2.3",

    "css-loader": "^0.23.1",

    "d3": "^4.6.0",

    "dom-align": "^1.4.0",

    "domkit": "0.0.1",

    "echarts": "^3.4.0",

    "echarts-for-react": "^1.1.6",

    "es6-promise": "^3.1.2",

    "exports-loader": "^0.6.3",

    "express": "^4.13.3",

    "file-loader": "^0.8.5",

    "highcharts": "^4.2.5",

    "immutable": "^3.8.1",

    "imports-loader": "^0.6.5",

    "less": "^2.6.0",

    "less-loader": "^2.2.2",

    "object-assign": "^1.0.0",

    "openlayers": "^3.20.0",

    "rc-queue-anim": "^0.11.9",

    "react": "^0.14.8",

    "react-dom": "^0.14.8",

    "react-height": "^2.1.0",

    "react-hot-loader": "^1.3.0",

    "react-redux": "^4.4.1",

    "react-router": "^2.0.1",

    "react-router-redux": "^4.0.0",

    "redux": "^3.3.1",

    "redux-logger": "^2.6.1",

    "redux-thunk": "^2.0.1",

    "socket.io-client": "^1.4.8",

    "style-loader": "^0.13.0",

    "url-loader": "^0.5.7",

    "webpack": "^1.12.14",

    "webpack-dev-middleware": "^1.5.1",

    "webpack-dev-server": "^1.14.1",

    "webpack-hot-middleware": "^2.10.0",

    "whatwg-fetch": "^0.11.0",

    "zingchart": "^2.5.2",

    "zingchart-react": "^1.0.5"

  },

  "main": "index.js",     //指定加载的入口文件  默认值模块根目录下的index.js

  "scripts": {            //指定运行脚本命令的npm命令行缩写  比如start指定了运行npm run start时所要执行的命令

    "start": "node server.js",

    "deploy": "webpack -p --config webpack.config.dist.js --colors --profile",

    "build": "webpack",

    "dev": "webpack-dev-server --hot --inline --devtool eval --progress --colors --content-base build --host 0.0.0.0",

    "test": "echo \"Error: no test specified\" && exit 1"

  },

  "author": "zly",

  "license": "ISC"

}

 

Webpack篇

5.安装webpack

  1)全局安装  $ npm install webpack -g

  2)当然如果常规项目还是把依赖写入 package.json 包去更人性化:

     $ npm init

     $ npm install webpack --save-dev

6.配置    

     每个项目下都必须配置有一个 webpack.config.js ,它的作用如同常规的 gulpfile.js/Gruntfile.js ,就是一个配置项,告诉 webpack 它需要做什么。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

var webpack = require('webpack');

var commonsPlugin = new webpack.optimize.CommonsChunkPlugin('common.js');

module.exports = {

    //插件项,使用CommonsChunkPlugin的插件,用于提取多个入口文件的公共脚本部分,然后生成一个common.js来方便页面之间进行复用

    plugins: [commonsPlugin],

    //页面入口文件配置

    entry: {

        index : './src/js/page/index.js'

    },

    //入口文件输出配置(入口文件最终要生成什么名字【index.js存放早path里面】的文件,存放到哪里)

    output: {

        path: 'dist/js/page',

        filename: '[name].js'

    },

    module: {

        //加载器配置

        loaders: [

              //.css 文件使用style-loader和css-loader来处理

            { test: /\.css$/, loader: 'style-loader!css-loader' },

              //.js 文件使用jsx-loader来编译处理

            { test: /\.js$/, loader: 'jsx-loader?harmony' },

              //.scss文件使用style-loader、css-loader 和 sass-loader 来编译处理

            { test: /\.scss$/, loader: 'style!css!sass?sourceMap'},

                 //图片文件使用 url-loader 来处理,小于8kb的直接转为base64

            { test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192'}

        ]

    },

    //其它解决方案配置

resolve: {

    //查找module的话从这里开始查找

        root: 'E:/github/flux-example/src', //绝对路径

        extensions: ['', '.js', '.json', '.scss'],//自动扩展文件后缀名意味着引入模块不需要加后缀

        alias: {  //模块别名定义,方便后续直接引用别名 无需多谢很长的地址

             AppStore : 'js/stores/AppStores.js',  //直接require(‘AppStore’)

            ActionType : 'js/actions/ActionType.js',

            AppAction : 'js/actions/AppAction.js'

        }

    }

};

Url-loader会将样式中引用到的图片转换成模块来处理,使用该加载器需要进行安装

npm install url-loader -save-dev

 

  1. 运行webpack

        执行 $ webpack --display-error-details

        其他主要参数

1

2

3

4

5

6

7

$ webpack --config XXX.js   //使用另一份配置文件(比如webpack.config2.js)来打包

 

$ webpack --watch   //监听变动并自动打包

 

$ webpack -p    //压缩混淆脚本,这个非常非常重要!

 

$ webpack -d    //生成map映射文件,告知哪些模块被最终打包到哪里了

 

  1. 模块引入

1)HTML:

   直接在页面中引入webpack最终生成的页面脚本

1

2

3

4

5

6

7

8

9

10

11

<!DOCTYPE html>

<html>

<head lang="en">

    <meta charset="UTF-8">

    <title>demo</title>

</head>

<body>

<script src="dist/js/page/common.js"></script>

<script src="dist/js/page/index.js"></script>

</body>

</html>

 

 

可以看到我们连样式都不用引入,毕竟脚本执行时会动态生成<style>并标签打到head里

2)JS:

各脚本模块可以直接使用 commonJS 来书写,并可以直接引入未经编译的模块,比如 JSX、sass、coffee等(只要你在 webpack.config.js 里配置好了对应的加载器)。

我们再看看编译前的页面入口文件(index.js):

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

require('../../css/reset.scss'); //加载初始化样式

require('../../css/allComponent.scss'); //加载组件样式

var React = require('react');

var AppWrap = require('../component/AppWrap'); //加载组件

var createRedux = require('redux').createRedux;

var Provider = require('redux/react').Provider;

var stores = require('AppStore');

 

var redux = createRedux(stores);

 

var App = React.createClass({

    render: function() {

        return (

            <Provider redux={redux}>

                {function() { return <AppWrap />; }}

            </Provider>

        );

    }

});

 

React.render(

    <App />, document.body

);

 

  1. 补充技巧

   1.shimming

在 AMD/CMD 中,我们需要对不符合规范的模块(比如一些直接返回全局变量的插件)进行 shim 处理,这时候我们需要使用 exports-loader 来帮忙:

{ test: require.resolve("./src/js/tool/swipe.js"),loader:"exports?swipe"}

之后再脚本中引用的时候

require('./tool/swipe.js');

swipe();

2.自定义公共模块提取

在文章开始我们使用了 CommonsChunkPlugin 插件来提取多个页面之间的公共模块,并将该模块打包为 common.js 。

但有时候我们希望能更加个性化一些,我们可以这样配置:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin");

module.exports = {

    entry: {

        p1: "./page1",

        p2: "./page2",

        p3: "./page3",

        ap1: "./admin/page1",

        ap2: "./admin/page2"

    },

    output: {

        filename: "[name].js"

    },

    plugins: [

        new CommonsChunkPlugin("admin-commons.js", ["ap1", "ap2"]),

        new CommonsChunkPlugin("commons.js", ["p1", "p2", "admin-commons.js"])

    ]

};

// <script>s required:

// page1.html: commons.js, p1.js

// page2.html: commons.js, p2.js

// page3.html: p3.js

// admin-page1.html: commons.js, admin-commons.js, ap1.js

// admin-page2.html: commons.js, admin-commons.js, ap2.js

3.独立打包样式文件

有时候可能希望项目的样式能不要被打包到脚本中,而是独立出来作为.css,然后在页面中以<link>标签引入。这时候我们需要 extract-text-webpack-plugin 来帮忙:

1

2

3

4

5

6

7

8

var webpack = require('webpack');

    var commonsPlugin = new webpack.optimize.CommonsChunkPlugin('common.js');

    var ExtractTextPlugin = require("extract-text-webpack-plugin");

 

    module.exports = {

        plugins: [commonsPlugin, new ExtractTextPlugin("[name].css")],

        entry: {

        //...省略其它配置

4.最终 webpack 执行后会乖乖地把样式文件提取出来:

       

5.使用CDN/远程文件

有时候我们希望某些模块走CDN并以<script>的形式挂载到页面上来加载,但又希望能在 webpack 的模块中使用上。

这时候我们可以在配置文件里使用 externals 属性来帮忙:

1

2

3

4

5

6

7

{

    externals: {

        // require("jquery") 是引用自外部模块的

        // 对应全局变量 jQuery

        "jquery": "jQuery"

    }

}

 

需要留意的是,得确保 CDN 文件必须在 webpack 打包文件引入之前先引入。

我们倒也可以使用 script.js 在脚本中来加载我们的模块:

var $script = require("scriptjs");

$script("//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js", function() {

   $('body').html('It works!')

});

 

6.与 grunt/gulp 配合

gulp.task("webpack", function(callback) {

    // run webpack

    webpack({

        // configuration

    }, function(err, stats) {

        if(err) throw new gutil.PluginError("webpack", err);

        gutil.log("[webpack]", stats.toString({

            // output options

        }));

        callback();

    });

});

 

posted @ 2017-04-07 15:45  Naomi❤  阅读(811)  评论(0编辑  收藏  举报