React技术栈——webpack

一直在用fis3,也能完美满足目前业务需求。我厂的scrat也有大量的feature贴合业务线。

最近在看React,要打通React的技术栈,学习Webpack是必不可少的了。

从npm上安装很简单:

npm install webpack -g

Webpack特色:

<li>模块化,支持异步和同步</li>
<li>Loader,把各种文件拆分成模块的支持</li>
<li>更机智的编译</li>
<li>插件系统,提供各色各样的插件,毫不逊色的其他打包工具,要什么价什么</li>

简单demo

先上第一个demo:

cats.js
var cats = ['dave', 'henry', 'martha'];
module.exports = cats;
app.js
var cats = require('./cats');
console.log('cats')

webpack登场:


webpack ./app.js app.bundle.js

这命令可以cats.js打包进app.js里面,最后生成app.bundle.js

利用配置文件来操作webpack

-webpack.config.js

module.exports = {
    entry: './src/app',
    output: {
        path: './bin',
        filename: 'app.bundle'
    }
}

配置完后,在文件夹直接webpack即可

使用loader

loader应该是webpack的预加载工具

module.exports = {
    entry: './src/app.js',
    output: {
        path: './bin',
        filename: 'app.bundle.js'
    },
    module: {
        loaders: [{
            test: /\.js$/,
            exclude: /node_moudles/,
            loader: 'babel-loader'
        }]
    }
}

使用plugins

module.exports = {
    entry: './src/app.js',
    output: {
        path: './bin',
        filename: 'app.bundle.js'
    },
    module: {
        loaders: [{
            test: /\.js$/,
            exclude: /node_moudles/,
            loader: 'babel-loader'
        }]
    },
    plugins: [
        new webapck.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            },
            output: {
                comments: false
            }
        })
    ]
}

CONFIGURATION OBJECT CONTENT

可以编写js,不仅仅是个json对象

entry


基本语法:
{
    context: _dirname + '/app',
    entry: './entry',
    output: {
        path: _dirname + '/dist',
        filename: 'bundle.js'
    }
}

传入object时
{
    entry: {
        page1: './page1',
        page2: ['./entry1', './entry2']
    },
    output: {
        filename: '[name].bundle.js',
        chunkFilename: '[id].bundle.js'
    }
}

output

multiple entries
{
    entry: {
        app: './src/app.js',
        search: './src/search.js'            
    },
    output: {
        filename: '[name].js',
        path: __dirname + '/built'            
    }
}

//outpu: ./built/app.js  ./built/search.js

output.pubicPath


适用于类似CDN匹配需求
可添加hash绕过缓存机制
output: {
    path: '/home/project/cdn/assets/[hash]',
    publicPath: "http://cdn.example.com/assets/[hash]/"
}

Watch

webpack有个很牛逼的地方,热刷新。

配置好文件后,下面命令可以监听文件变化

webpack --watch 

在配置文件里一样可以实现:

module.exports = {
    entry: {
        app: './src/app.js'
    },
    output: {
        filename: 'bundle.js',
    },
    watch: true
}

在做网页开发时候,需要用到服务器,webpack提供了webpack-dev-server

安装很简单:

npm install webpack-dev-server -g

demo:

webpack-dev-server --host 0.0.0.0 --port 8080 --inline
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值