webpack踩过的坑(总结)

使用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;
    }
}

 

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",
    }

 



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'
})

//extract-text-webpack-plugin 同时使用style-loader和postcss-loader时会报错,将style-loader移除
ExtractTextPlugin.extract(["css-loader", "postcss-loader"])

完整的配置文件

var fs = require('fs');
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");// 默认的webpack 会将require("style.css")文件嵌入js文件中,使用该插件会将css从js中提取出来
var CleanWebpackPlugin = require('clean-webpack-plugin'); // 删除文件
var CopyWebpackPlugin = require('copy-webpack-plugin'); // 拷贝文件
var BomPlugin = require('webpack-utf8-bom');//将文件转成utf-8 bom格式,解决中文乱码的问题
var autoprefixer = require('autoprefixer')
var cssparams = JSON.stringify({ discardComments: { removeAll: false } });

var htmlMinifyOptions = require('./htmlminify.config.js'); //htmlminify的配置参数


//定义了一些文件夹的路径
var ROOT_PATH = path.resolve(__dirname);
var HTML_ROOT_PATH = path.resolve(__dirname, "html");
var HTML_SRC_PATH = path.resolve(ROOT_PATH, 'dev');
var HTML_DIST_PATH = path.resolve(ROOT_PATH, 'dist');

// 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 config = {
    entry: {
        index: path.resolve(HTML_SRC_PATH, 'index.js'),
        vendors: ['jquery'],
    },
    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",
    },
    plugins: [
        new ExtractTextPlugin("styles/[name].[contenthash:6].css", { allChunks: false /*是否将分散的css文件合并成一个文件*/ }),
        new CommonsChunkPlugin('vendors', 'vendors.[hash:6].js'),
        new CleanWebpackPlugin(['dist', 'build'], {
            root: ROOT_PATH,
            verbose: true,
            dry: false,
            //exclude: ["dist/1.chunk.js"]
        }),
        //new webpack.optimize.UglifyJsPlugin({
        //    beautify: true,
        //    compress: { warnings: false, },
        //    output: { comments: true }
        //}),
        //new BomPlugin(true, /\.(cshtml)$/),//解决cshtml中文乱码的问题
    ],
    module: {
        // 解决动态js url警告错误
        unknownContextRegExp: /$^/,
        unknownContextCritical: false,

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

        // require("prefix" + expr + "surfix")
        wrappedContextRegExp: /$^/,
        wrappedContextCritical: false,
        // end
        loaders: [
            { test: require.resolve('jquery'), loader: 'expose?$!expose?jQuery' },// 将jQuery暴露到全局变量中
            {
                test: /\.css$/,
                loader: ExtractTextPlugin.extract(["css-loader", "postcss-loader"]) //同时使用style-loader和postcss-loader时会报错,将style-loader移除
            },
            { test: /\.(woff|woff2|eot|ttf|svg)(\?[a-z0-9]+)?$/, loader: 'url-loader?limit=1000&name=styles/fonts/[name].[hash:6].[ext]' }, // 处理图片url
            { test: /\.(png|jpg|gif)(\?[a-z0-9]+)?$/, loader: 'url-loader?limit=1000&name=styles/images/[name].[hash:8].[ext]' }, // 处理图片url limit=1000 小于1kb则生成base64
            //{ test: /\.css$/, loaders: ['style-loader', 'css-loader', 'postcss-loader'] },
            {
                test: /\.js$/,
                exclude: /(node_modules|bower_components)/,
                loader: 'babel', // 'babel-loader' is also a valid name to reference
                query: {
                    presets: ['es2015']
                }
            },
            { test: /\.tpl/, loader: 'art-template-loader' },
        ]
    },
    postcss: [autoprefixer()],
    resolve: {
        alias: {
            "datepicker": "jquery-ui/ui/widgets/datepicker",
        }
    }
};
// 遍历所有.html文件,使用HtmlWebpackPlugin将资源文件引入html中
var htmlfiles = fs.readdirSync(HTML_ROOT_PATH);
htmlfiles.forEach(function (item) {
    var currentpath = path.join(HTML_ROOT_PATH, item);
    //console.log(currentpath);
    var extname = path.extname(currentpath);
    if (fs.statSync(currentpath).isFile()) {
        //console.log("replace", currentpath.replace("\\html\\", "\\dist\\"))
        config.plugins.push(new HtmlWebpackPlugin({
            title: '',
            template: currentpath,
            filename: currentpath.replace("\\html\\", "\\dist\\"),
            minify: isprod ? htmlMinifyOptions : false, // 生产模式下压缩html文件
            //chunks: ['index', 'vendors'],   // 配置该html文件要添加的模块
            inject: 'body'
        }))
    }
});

module.exports = config;

 

转载于:https://www.cnblogs.com/RuMengkai/p/6649384.html

你可能感兴趣的:(webpack踩过的坑(总结))