webpack总结

其实很多东西都是以前用到过得,之所以再过一遍也是为了加深印象。

1.概念

Webpack是一款用户打包前端模块的工具。主要是用来打包在浏览器端使用的javascript的。同时也能转换、捆绑、打包其他的静态资源,包括css、image、font file、template等。

2.安装 npm install webpack -g

3.webpack配置

webpack需要编写一个config文件,然后根据这个文件来执行需要的打包功能。命名为webpack-config.js。config文件实际上就是一个Commonjs的模块。举例如下:

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

module.exports = {
    entry: {
        app: './src/app', //编译的入口文件
    },
    output: {
        publicPath: '/build/', //服务器根路径
        path: './static/build', //编译到当前目录
        filename: '[name].js' //编译后的文件名字
    },
    module: {
        loaders: [{
            test: /\.js$/,
            exclude: /^node_modules$/,
            loader: 'babel?presets=es2015'
        }, {
            test: /\.css$/,
            exclude: /^node_modules$/,
            loader: ExtractTextPlugin.extract('style-loader', 'css-loader!autoprefixer-loader')
        }, {
            test: /\.less/,
            exclude: /^node_modules$/,
            loader: ExtractTextPlugin.extract('style-loader', 'css-loader!autoprefixer-loader!less-loader')
        }, {
            test: /\.(eot|woff|svg|ttf|woff2|gif|appcache)(\?|$)/,
            exclude: /^node_modules$/,
            loader: 'file-loader?name=[name].[ext]'
        }, {
            test: /\.(png|jpg)$/,
            exclude: /^node_modules$/,
            loader: 'url?limit=20000&name=[name].[ext]' //注意后面那个limit的参数,当你图片大小小于这个限制的时候,会自动启用base64编码图片
        }, {
            test: /\.jsx$/,
            exclude: /^node_modules$/,
            loaders: ['jsx', 'babel?presets[]=es2015,presets[]=react']
        }]
    },
    plugins: [
        new webpack.DefinePlugin({ //编译成生产版本
            'process.env': {
                NODE_ENV: JSON.stringify('production')
            }
        }),
        new ExtractTextPlugin('[name].css')
    ],
    resolve: {
        extensions: ['', '.js', '.jsx'], //后缀名自动补全
    }
};

entry:配置要打包的文件的入口;可以配置多个入口文件;

resolve:配置文件后缀名(extensions),除了js,还有jsx、coffee等等。alias配置项,可以为常用模块配置改属性,可以节省编译的搜索时间.

output:配置输出文件的路径,文件名等。

modules(loaders):配置要使用的loader。把资源文件(css、图片、html等非js模块)处理成相应的js模块,然后其它的plugins才能对这些资源进行下一步处理。比如babel-loader可以把es6的文件转换成es5。大部分的对文件的处理的功能都是通过loader实现的。loader可以用来处理在入口文件中require的和其他方式引用进来的文件。loader一般是一个独立的node模块,要单独安装。

loader配置项:

test: /\.(js|jsx)$/,           //注意是正则表达式,不要加引号,匹配要处理的文件
loader: 'eslint-loader',       //要使用的loader,"-loader"可以省略
include: [path.resolve(__dirname, "src/app")],   //把要处理的目录包括进来
exclude: [nodeModulesPath]     //排除不处理的目录

 

plugins:配置要使用的插件。plugin是比loader功能更强大的插件,能使用更多的wepack api

 

posted @ 2017-02-14 16:14  李元夕cool  阅读(193)  评论(0编辑  收藏  举报