webpack使用笔记(一)

1、使用process.argv 获取命令行使用的参数

// 判断是否带production参数,production会压缩js
var isprod = false;
for (var i in process.argv) {
    if (process.argv[i] === "-p" || process.argv[i] === "--production") {
        isprod = true;
        break;
    }
}

2、url-loader 路径不正确,可通过 publicPath进行配置

output: {
        //context: path.resolve(__dirname, 'scripts'),
        path: path.resolve(HTML_DIST_PATH, "assets"),
        publicPath: '/dist/assets/',//当生成的资源文件和站点不在同一地方时需要配置改地址 e.g.:站点在src,资源生成到/src/static/dist,那么publicPath="/static/dist"
        filename: "[name].[hash:6].js",
        chunkFilename: "[id].chunk.js",
    }

3、html-webpack-plugin minify: true 报错,请改成具体的参数

new HtmlWebpackPlugin({
    title: '',
    template: currentpath,
    filename: currentpath.replace("\\html\\", "\\dist\\"),
    minify: {
        "removeAttributeQuotes": true,
        "removeComments": true,
        "removeEmptyAttributes": true,
    }
    //chunks: ['index', 'vendors'],   // 配置该html文件要添加的模块
    inject: 'body'
})

4、使用art-template时可以先将模板文件进行压缩在预编译

loaders: [
    // 先对html模板文件进行压缩再预编
    { test: /\.tpl/, loader: 'art-template!html-minifier' },
]

5、使用postcss编译css文件时,可以将postcss的配置文件写入单独的postcss.config.js文件中

...
module: {
    ....
},
// 也可以将该配置移除,单独一个配置文件postcss.config.js
postcss: [postcss(), autoprefixer()],
...

6、使用HtmlWebpackPlugin压缩html时,minify配置参数可从node_modules\html-minifier\sample-cli-config-file.conf获取。

sample-cli-config-file.conf的配置是比较完整的,请根据自己的情况删减配置。可将ample-cli-config-file.conf里面的配置写入htmlminify.config.js文件中,然后再webpack文件中使用

var htmlMinifyOptions = require('./htmlminify.config.js'); //htmlminify的配置参数
...
plugins: [
    new HtmlWebpackPlugin({
        title: '后台管理 . NOCOQ',
        template: path.resolve(CTRL_ROOT_PATH, 'views/home/index_tpl.cshtml'),
        filename: path.resolve(CTRL_ROOT_PATH, 'views/home/index.cshtml'),
        minify: isprod ? htmlMinifyOptions : false, // 生产模式下压缩html文件
        chunks: ['index', 'vendors'],   // 配置要添加的模块
        inject: 'body'
    }),
],
...

7、配置一个简短的命令,方便在cmd中快速执行

每次运行webpack命令时,总是要写一长串的命令,如:webpack –config webpack.admin.config.js –proccess –color,每次都这样子写,很麻烦!我们可以在package.json文件中配置一些我们经常使用的命令;在package.json添加scripts节点:

"scripts": {
    "admin-build": "webpack --config webpack.admin.config.js --proccess --color",
    "admin-watch": "webpack --config webpack.admin.config.js --proccess --color --watch",
    "admin-release": "webpack --config webpack.admin.config.js --proccess --color -p",
}

然后就可以在命令行中输入简短命令 npm run admin-build 执行了。

8、加载器的执行顺序是从右开始的。

所以请把html-minifier放在art-template的右边,把sass-loader放在css-loader的右边

// 先对html模板文件进行压缩再预编
{ test: /\.tpl/, loader: 'art-template!html-minifier' },
{
    test: /\.scss$/,
    loader: ExtractTextPlugin.extract(["css-loader?sourceMap", "postcss-loader", "sass-loader?sourceMap"]) 
}

如果对你有帮助,请捐赠共勉(微信支付)
webpack使用笔记(一)_第1张图片

以下是一个完整的webpack配置文件

//webpack.config.js
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin'); // 自动写入将引用写入html
var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin"); // 提取公共模块
var ExtractTextPlugin = require("extract-text-webpack-plugin");// 提取/分离css
var CleanWebpackPlugin = require('clean-webpack-plugin'); // 删除文件
var CopyWebpackPlugin = require('copy-webpack-plugin'); // 拷贝文件
var BomPlugin = require('webpack-utf8-bom');//将文件转成utf-8 bom格式,解决中文乱码的问题
var postcss = require('postcss');
var autoprefixer = require('autoprefixer');

// process.argv 获取命令行使用的参数
// 判断是否带production参数,production会压缩js
var isprod = false;
for (var i in process.argv) {
    if (process.argv[i] === "-p" || process.argv[i] === "--production") {
        isprod = true;
        break;
    }
}

//定义了一些文件夹的路径
var ROOT_PATH = path.resolve(__dirname);
var CTRL_ROOT_PATH = path.resolve(__dirname, "administration");
var JS_SRC_PATH = path.resolve(CTRL_ROOT_PATH, 'dev');
var STATIC_SRC_PATH = path.resolve(CTRL_ROOT_PATH, "static_src");
var STATIC_DIST_PATH = path.resolve(CTRL_ROOT_PATH, 'static');

var cssparams = JSON.stringify({ sourceMap: true, discardComments: { removeAll: isprod } });
var htmlMinifyOptions = require('./htmlminify.config.js'); //htmlminify的配置参数



var JS_PATH_FORMAT = "[name]" + (isprod ? ".[hash:6]" : "") + ".js";
var CSS_PATH_FORMAT = "styles/[name]" + (isprod ? ".[contenthash:6]" : "") + ".css";
var FONT_PATH_FORMAT = "fonts/[name]" + (isprod ? ".[hash:6]" : "") + ".[ext]";
var IMG_PATH_FORMAT = "images/[name]" + (isprod ? ".[hash:6]" : "") + ".[ext]";
var VENDORS_PATH_FORMAT = "vendors" + (isprod ? ".[hash:6]" : "") + ".js";


module.exports = {
    entry: {

        index: path.resolve(JS_SRC_PATH, 'index.js'),
        login_index: path.resolve(JS_SRC_PATH, 'login_index.js'),
        vendors: ['jquery', 'datepicker'],
        //"jquery-ui": ["jquery-ui/themes/base/core.css", "jquery-ui/themes/base/datepicker.css", "jquery-ui/themes/base/theme.css"],
        //"style": [path.resolve(JS_SRC_PATH, 'styles/style.css')],
    },
    output: {
        //context: path.resolve(__dirname, 'scripts'),
        path: path.resolve(STATIC_DIST_PATH),
        publicPath: '/administration/static/',//当生成的资源文件和站点不在同一地方时需要配置改地址 e.g.:站点在src,资源生成到/src/static/dist,那么publicPath="/static/dist"
        filename: JS_PATH_FORMAT,
        chunkFilename: "[id].chunk.js",
    },
    devtool: "source-map",
    plugins: [
        //new webpack.ProvidePlugin({$: 'jquery'}),
        new ExtractTextPlugin(CSS_PATH_FORMAT, { allChunks: false }),
        new HtmlWebpackPlugin({
            title: '后台管理 . NOCOQ',
            template: path.resolve(CTRL_ROOT_PATH, 'views/home/index_tpl.cshtml'),
            filename: path.resolve(CTRL_ROOT_PATH, 'views/home/index.cshtml'),
            minify: isprod ? htmlMinifyOptions : false, // 生产模式下压缩html文件
            chunks: ['index', 'vendors'],   // 配置要添加的模块
            inject: 'body'
        }),
        new HtmlWebpackPlugin({
            title: '登录后台管理 . NOCOQ',
            template: path.resolve(CTRL_ROOT_PATH, 'views/account/login_tpl.cshtml'),
            filename: path.resolve(CTRL_ROOT_PATH, 'views/account/login.cshtml'),
            minify: isprod ? htmlMinifyOptions : false, // 生产模式下压缩html文件
            chunks: ['login_index', 'vendors'],   // 配置要添加的模块
            inject: 'body'
        }),
        new CommonsChunkPlugin('vendors', VENDORS_PATH_FORMAT),
        new CleanWebpackPlugin(['static', 'build'], {
            root: CTRL_ROOT_PATH,
            verbose: true,
            dry: false,
            //exclude: ["dist/1.chunk.js"]
        }),
        new BomPlugin(true, /\.(cshtml)$/),//解决cshtml中文乱码的问题
        //new CopyWebpackPlugin([{
        //    from: 'faces', to: 'faces'
        //}]),
        /*new webpack.optimize.UglifyJsPlugin({
            //beautify: false,
            compress: {
                warnings: false,
            },
            output: {
                comments: false
            }
        }),*/
    ],
    module: {
        // require
        unknownContextRegExp: /$^/,
        unknownContextCritical: false,

        // require(expr)
        exprContextRegExp: /$^/,
        exprContextCritical: false,

        // require("prefix" + expr + "surfix")
        wrappedContextRegExp: /$^/,
        wrappedContextCritical: false,

        loaders: [
            { test: require.resolve('jquery'), loader: 'expose?$!expose?jQuery' },// 将jQuery暴露到全局变量中
            {
                test: /\.css$/,
                loader: ExtractTextPlugin.extract(["css-loader?" + cssparams, "postcss-loader"]) //同时使用style-loader和postcss-loader时会报错,将style-loader移除
            },
            {
                test: /\.scss$/,
                loader: ExtractTextPlugin.extract(["css-loader?sourceMap", "postcss-loader", "sass-loader?sourceMap"]) //同时使用style-loader和postcss-loader时会报错,将style-loader移除
            },
            { test: /\.(woff|woff2|eot|ttf|svg)(\?[a-z0-9]+)?$/, loader: 'url-loader?limit=1000&name=' + FONT_PATH_FORMAT }, // 处理图片url
            { test: /\.(png|jpg|gif)(\?[a-z0-9]+)?$/, loader: 'url-loader?limit=1000&name=' + IMG_PATH_FORMAT }, // 处理图片url limit=1000 小于1kb则生成base64
            {
                test: /\.js$/,
                exclude: /(node_modules|bower_components)/,
                loader: 'babel', // 'babel-loader' is also a valid name to reference
                query: {
                    presets: ['es2015']
                }
            },
            // 先对html模板文件进行压缩再预编
            { test: /\.tpl/, loader: 'art-template!html-minifier' },
        ]
    },
    postcss: [postcss(), autoprefixer()],
    resolve: {
        alias: {
            "datepicker": "jquery-ui/ui/widgets/datepicker",
        }
    }
};

你可能感兴趣的:(webpack)