美文网首页
关于webpack多页面配置部分记录

关于webpack多页面配置部分记录

作者: black白先森 | 来源:发表于2017-11-01 19:54 被阅读119次
    1.jpg

    注意这个页面中的css,js,img资源,用的是webpack.config.js 的publicPath

    module.exports = {
        devtool: '#source-map',
        entry: entry_files,
        output: {
            filename: 'static/js/[name][hash].js',
            chunkFilename: './static/js/[id].chunk.js',
            path: path.join(__dirname, 'dist'),
            //publicPath 上线替换真实的http,如果设置为/则需把dist下的文件放在项目的根目录
            //publicPath:'http://localhost:3000/'
            publicPath:'./'
        // 这里的publicPath注意,后来HtmlWebpack插件资源注入页面模板时,是在这个地址下的
        },
    
    目录.jpg
        module: {
            rules: [
                {
                    test: /\.js$/,
                    exclude: /(node_modules|bower_components)/,
                    loader: 'babel-loader'
                },
                {
                    test: /\.css$/,
                    use: ExtractTextPlugin.extract({
                        fallback: "style-loader",
                        use:[
                            {
                                loader: 'css-loader',
                                options:{
                                    minimize: true //css压缩
                                }
                            }
                        ]
                    })
                },
                {
                    test: /\.scss$/,
                    use: ExtractTextPlugin.extract({
                        fallback: 'style-loader',
                        use: ['css-loader', 'sass-loader']
                    })
                },
                {
                    test: /\.html$/,
                    loader: "html-loader?attrs=img:src img:data-src"
                },
    

    utils.js 判断生产环境,开发环境

    var path = require('path');
    const fs = require('fs');
    /*设置生产环境与开发环境路径*/
    exports.assetsPath = function (_path) {
        var assetsSubDirectory = process.env.NODE_ENV === 'production'
            ? 'static'
            : 'static'
        return path.posix.join(assetsSubDirectory, _path)
    }
    
                {
                    test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
                    loader: 'url-loader',
                    options: {
                        limit:10000,
                        name:utils.assetsPath('img/[name].[hash:7].[ext]')
                    }
                },
                {
                    test:/\.(woff2?|eot|ttf|otf)(\?.*)?$/,
                    loader: 'url-loader',
                    options: {
                        limit: 10000,
                        name: utils.assetsPath('fonts/[name].[ext]')
                    }
                }           
            ]
    
        },
        plugins: require('./base.plugin'),
        //方便开发使用,浏览器输入:http://localhost:3000访问
        devServer:{
            contentBase:'./',
            host:'localhost',
            compress:true,
            port:3000,
            inline:true
        }
    }
    

    原来html中没有css,js引入 是统一引入同名资源

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>index</title>
    </head>
    <body>
    <div class="container">
        <div class="row">
            <div><p>index</p></div>
            <div class="col-md-12 tcon">
            </div>
        </div>
        <div class="row">
            <div class="col-md-6">
              <img >
            </div>
        </div>
    </div>
    </body>
    </html>
    

    entry.js 中把src/js下面的文件存储

    var path = require('path');
    var fs = require('fs');
    let entry_files = {};
    
    function each_file(dir) {
        try {
            console.log(fs.readdirSync(dir))
            /**
            [ 'index.js',
              'mod.js',
              'pageA.js',
              'pageB.js',
              'pageC.js',
              'testm.js' ]
            */
            fs.readdirSync(dir).forEach(function (file) {
                var file_path = dir + '/' + file;
                var fname = path.basename(file, '.js');
                entry_files[fname]=file_path;
            })
            console.log(entry_files)
            /**
            { index: './src/js/index.js',
              mod: './src/js/mod.js',
              pageA: './src/js/pageA.js',
              pageB: './src/js/pageB.js',
              pageC: './src/js/pageC.js',
              testm: './src/js/testm.js'
            }
            */
        } catch (e) {
    
        }
    }
    each_file('./src/js');
    
    module.exports=entry_files;
    

    pagesArray.js

    var path = require('path');
    var fs = require('fs');
    let pagesArray = [];
    function each_file(dir) {
        try {
            fs.readdirSync(dir).forEach(function (file) {
                /*
                * {
                *   index:'./src/index.html',
                *   chunkname:'index'
                * }
                * */
                var file_obj={}; 
                var file_path = dir + '/' + file;
                var chunk_name = path.basename(file, '.html');
                file_obj['filename']=file;
                file_obj['template']=file_path;
                file_obj['chuckName']=chunk_name;
                pagesArray.push(file_obj)
    
                console.log(pagesArray)
    
                /*
                [ { filename: 'index.html',
                    template: './src/pages/index.html',
                    chuckName: 'index' },
                  { filename: 'pageA.html',
                    template: './src/pages/pageA.html',
                    chuckName: 'pageA' },
                  { filename: 'pageB.html',
                    template: './src/pages/pageB.html',
                    chuckName: 'pageB' },
                  { filename: 'pageC.html',
                    template: './src/pages/pageC.html',
                    chuckName: 'pageC' } ]*/
            })
        } catch (e) {
    
        }
    }
    each_file('./src/pages');
    module.exports=pagesArray;
    
    var path = require('path');
    var webpack = require('webpack');
    var HtmlWebpackPlugin = require('html-webpack-plugin');
    var ExtractTextPlugin = require("extract-text-webpack-plugin");
    //html页面 pagesArray
    var pagesArray =require('./pagesArray');
    let base_plugin = [
        new webpack.optimize.CommonsChunkPlugin({
            name: "vendors",
            chunks: ["pageA", "pageB", "pageC"],//提取公用模块
            minChunks: Infinity
        }),
        new ExtractTextPlugin({
            //生成css文件名
            filename: 'static/css/[name].css',
            disable: false,
            allChunks: true
        }),
        //webpack自带的js压缩插件
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        })
        /* new UglifyJSPlugin()*/
    ]
    /*遍历页面,添加配置*/
    pagesArray.forEach((page)=>{
        const htmlPlugin = new HtmlWebpackPlugin({
            template: page.template,
            filename: page.filename,
            chunks: ['vendors', page.chuckName],
            // hash:true,
            minify: {
                removeComments: true,
                collapseWhitespace: false //删除空白符与换行符
            }
        });
    
        // console.log(htmlPlugin)
    
        /*HtmlWebpackPlugin {
            options: { template: './src/pages/pageA.html',
                 filename: 'pageA.html',
                 hash: false,
                 inject: true,
                 compile: true,
                 favicon: false,
                 minify: { removeComments: true, collapseWhitespace: false },
                 cache: true,
                 showErrors: true,
                 chunks: [ 'vendors', 'pageA' ],
                 excludeChunks: [],
                 title: 'Webpack App',
                 xhtml: false 
             } 
         }*/
    
        base_plugin.push(htmlPlugin)
    })
    
    module.exports = base_plugin;
    

    相关文章

      网友评论

          本文标题:关于webpack多页面配置部分记录

          本文链接:https://www.haomeiwen.com/subject/oeagpxtx.html