shaozj / blog

blog
87 stars 4 forks source link

webpack 多页面构建 #11

Open shaozj opened 7 years ago

shaozj commented 7 years ago

目标:

配置文件编写(webpack.config.js)

示例:

var path = require('path');
var glob = require('glob');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var node_dir = path.join(__dirname, './node_modules/');
var HtmlWebpackPlugin = require('html-webpack-plugin');

// 获取所有入口文件
var getEntry = function(globPath) {
    var entries = {
        vendor: ['jquery','react','react-dom','./src/app'] // 类库
    };
    glob.sync(globPath).forEach(function(entry) {
        var pathname = entry.split('/').splice(-2).join('/').split('.')[0];
        entries[pathname] = [entry];
    });
    console.log(entries);
    return entries;
};
// 判断是否是在当前生产环境
var isProduction = process.env.NODE_ENV === 'production';
var entries = getEntry('./src/view/*/*.jsx');
var chunks = Object.keys(entries);
module.exports = {
    entry: entries,
    output: {
        path: path.join(__dirname, './dist'),
        filename: isProduction ?'js/[name].[hash:8].js':'js/[name].js',
        publicPath: '/dist/',
        chunkFilename: 'chunk/[name].chunk.js'
    },
    module: {
        noParse:[
            /*path.join(node_dir,'./react/dist/react.min.js'),
            path.join(node_dir,'./jquery/dist/jquery.min.js'),
            path.join(node_dir,'./react-dom/dist/react-dom.min.js')*/
        ],
        loaders: [{
            test: /\.jsx?$/,
            loader: 'babel',
            query: {
                presets: ['es2015', 'react']
            },
            exclude: node_dir
        }, {
            test: /\.css$/,
            loader: ExtractTextPlugin.extract('style', 'css')
        }, {
            test: /\.less$/,
            loader: ExtractTextPlugin.extract('style', 'css!less')
        }, {
            test: /\.(png|jpe?g|gif)$/,
            loader: 'url?limit=8192&name=img/[hash:8].[ext]'
        }, {
            //文件加载器,处理文件静态资源
            test: /\.(woff|woff2|ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
            loader: 'file?limit=10000&name=fonts/[hash:8].[ext]'
        }]
    },
    resolve: {
        extensions: ['', '.js', '.jsx', '.json'],
        alias: {
            mod: node_dir
        }
    },
    plugins: [
        new webpack.ProvidePlugin({
            $: 'jquery', // 使jquery变成全局变量,不用在自己文件require('jquery')了
            jQuery: 'jquery',
            React: 'react',
            ReactDOM: 'react-dom'
        }),
        // 类库统一打包生成一个文件
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor',
            filename: isProduction ? 'js/vendor.[hash:8].js':'js/vendor.js',
            minChunks: 3 // 提取使用3次以上的模块,打包到vendor里
        }),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        }),
        new ExtractTextPlugin(isProduction ? 'css/[name].[hash:8].css':'css/[name].css')
    ],
    devtool: isProduction ? null : 'source-map'
};
// 生成HTML文件
chunks.forEach(function(pathname) {
    if (pathname == 'vendor') {
        return;
    }
    var conf = {
        title: 'My App',
        filename: isProduction? '../view/' + pathname + '.html' : pathname + '.html',
        template: './src/template.html',
        inject: 'body',
        minify: {
            removeComments: true,
            collapseWhitespace: false
        }
    };
    if (pathname in module.exports.entry) {
        conf.chunks = ['vendor', pathname];
        conf.hash = false;
    }
    module.exports.plugins.push(new HtmlWebpackPlugin(conf));
});

Webpack的配置主要包括以下几大项目:

webpack 常用命令

webpack dev server

参考文档:

webpack 多页面构建

  1. 使用 React 写个简单的活动页面运营系统
  2. Webpack+React多页面应用探索
  3. webpack不适合多页面应用?你写的插件还不够多
  4. 【AlloyTeam优化系列】构建篇

webpack react generator

  1. generator-react-webpack

webpack 构建优化

  1. 开发工具心得:如何 10 倍提高你的 Webpack 构建效率
  2. webpack使用优化(基本篇)
  3. webpack使用优化(react篇)
  4. webpack 的 dll 功能
  5. https://zhuanlan.zhihu.com/p/21748318

webpack-dev-server

  1. webpack-dev-server使用方法
  2. WEBPACK DEV SERVER

多入口以及code-splitting

  1. webpack multiple-entry-points example
  2. MULTIPLE ENTRY POINTS
  3. CODE SPLITTING

webpack 配置
16.详解前端模块化工具-Webpack 不错的文章

  1. 【翻译】Webpack——令人困惑的地方好文章

webpack CommonsChunkPlugin详细教程
18.webpack CommonsChunkPlugin详细教程

iceberg211 commented 7 years ago

学习了,给楼主点个赞!

fenqiang4952 commented 7 years ago

谢谢了,真的很有帮助。

zivyangll commented 7 years ago

good

xieyihao commented 7 years ago

Good!

jinjidecoco commented 7 years ago

npm run dev 出现了这个问题 Refused to apply inline style because it violates the following Content Security Policy directive: "default-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-cEmJ9wfQpnZLR35+jGeZk1WmknBbXo0CyiXREeJHUGo='), or a nonce ('nonce-...') is required to enable inline execution. Note also that 'style-src' was not explicitly set, so 'default-src' is used as a fallback.

BenesX commented 6 years ago

get

nokelong commented 5 years ago

是否遇到多次运行会重复插入script 脚本情况呢