1. 程式人生 > >webpack使用和踩過的坑

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;