使用了同步方式的code splitting(配置),页面就显白了,也没有没错,不知道怎么回事,请求老师帮助。

来源:4-4 Webpack 和 Code Splitting(2)

他门说这就是人生

2019-10-17

我贴一下我的配置:

package.json:

{
  "sideEffects": [
    "*.css",
    "*.scss",
    "*.less"
  ],
  "scripts": {
    "dev": "webpack --config ./build/webpack.dev.js",
    "serve": "webpack-dev-server --config ./build/webpack.dev.js",
    "build": "webpack --config ./build/webpack.prod.js"
  },
  "devDependencies": {
    "@babel/core": "^7.6.4",
    "@babel/preset-env": "^7.6.3",
    "animate.css": "^3.7.2",
    "autoprefixer": "^9.6.4",
    "axios": "^0.19.0",
    "babel-loader": "^8.0.6",
    "better-scroll": "^2.0.0-beta.2",
    "bootstrap": "^4.3.1",
    "bootstrap-notify": "^3.1.3",
    "bootstrap-table": "^1.15.5",
    "core-js": "^3.2.1",
    "css-loader": "^3.2.0",
    "ejs-loader": "^0.3.5",
    "fibers": "^4.0.1",
    "file-loader": "^4.2.0",
    "html-loader": "^0.5.5",
    "html-webpack-plugin": "^3.2.0",
    "jquery": "^3.4.1",
    "jquery-serializejson": "^2.9.0",
    "less": "^3.10.3",
    "less-loader": "^5.0.0",
    "node-sass": "^4.12.0",
    "popper.js": "^1.15.0",
    "postcss-loader": "^3.0.0",
    "sass": "^1.23.0",
    "sass-loader": "^8.0.0",
    "style-loader": "^1.0.0",
    "url-loader": "^2.2.0",
    "webpack": "^4.41.1",
    "webpack-cli": "^3.3.9",
    "webpack-dev-server": "^3.8.2",
    "webpack-merge": "^4.2.2",
    "ztree": "^3.5.24"
  },
  "dependencies": {
    "@babel/polyfill": "^7.6.0",
    "better-scroll": "^2.0.0-beta.2",
    "core-js": "^3.2.1"
  }
}

.babelrc:

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "corejs": 3,
        "useBuiltIns": "usage"
      }
    ]
  ]
}

webpack.common.js:

var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require("path")
module.exports = {
    context: path.join(__dirname, "../src"),
    entry: {
        home: "../src/scripts/pages/home/index.js",
        userManagement: '../src/scripts/pages/userManagement/index.js',
        roleManagement: '../src/scripts/pages/roleManagement/index.js',
        menuManagement: '../src/scripts/pages/menuManagement/index.js'
    },
    output: {
        filename: "[name].js",
        path: path.resolve(__dirname, "../src/main/resources/static")
    },
    module: {
        rules: [
            {
                test: /\.html$/,
                use: [
                    {
                        loader: 'html-loader',
                        options: {
                            minimize: true
                        }
                    }
                ]
            },
            {
                test: /\.(css)$/,
                use: [
                    {
                        loader: 'style-loader', // inject CSS to page
                    },
                    {
                        loader: 'css-loader', // translates CSS into CommonJS modules
                        options: {
                            //默认全局,想用局部的地方自己加:local
                            modules: 'global'
                        }
                    },
                    {
                        loader: 'postcss-loader', // Run postcss actions
                        options: {
                            plugins: function () { // postcss plugins, can be exported to postcss.config.js
                                return [
                                    require('autoprefixer')
                                ];
                            }
                        }
                    }
                ]
            },
            {
                test: /\.(scss)$/,
                use: [
                    {
                        loader: 'style-loader', // inject CSS to page
                    },
                    {
                        loader: 'css-loader', // translates CSS into CommonJS modules
                        options: {
                            modules: false
                        }
                    },
                    {
                        loader: 'postcss-loader', // Run postcss actions
                        options: {
                            plugins: function () { // postcss plugins, can be exported to postcss.config.js
                                return [
                                    require('autoprefixer')
                                ];
                            }
                        }
                    },
                    {
                        loader: 'sass-loader' // compiles Sass to CSS
                    }
                ]
            },
            {
                test: /\.(less)$/,
                use: [
                    {
                        loader: 'style-loader', // inject CSS to page
                    },
                    {
                        loader: 'css-loader', // translates CSS into CommonJS modules
                        options: {
                            modules: false
                        }
                    },
                    {
                        loader: 'postcss-loader', // Run postcss actions
                        options: {
                            plugins: function () { // postcss plugins, can be exported to postcss.config.js
                                return [
                                    require('autoprefixer')
                                ];
                            }
                        }
                    },
                    {
                        loader: 'less-loader' // compiles Sass to CSS
                    }
                ]
            },
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: "babel-loader"
            },
            {
                test: /\.(png|jpg|gif)$/,
                use: [
                    {
                        loader: 'url-loader',
                        options: {
                            //10KB以下则打包成DataURL,不打包成文件
                            limit: 10240,
                            useRelativePath: true
                        }
                    }
                ]
            },
            {
                test: /\.(woff|woff2|eot|ttf|otf)$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {}
                    }
                ]
            }
        ]
    },
    optimization: {
        usedExports: true,
        // splitChunks: {
        //     chunks: 'all'
        // }
    },
    plugins: [
        new HtmlWebpackPlugin({
            filename: "home.html",
            template: "../src/scripts/pages/home/template.html",
            meta: {
                'viewport': 'width=device-width, initial-scale=1, shrink-to-fit=no'
            },
            chunks: ['home']
        }),
        new HtmlWebpackPlugin({
            filename: "userManagement.html",
            template: "../src/scripts/pages/userManagement/template.html",
            meta: {
                'viewport': 'width=device-width, initial-scale=1, shrink-to-fit=no'
            },
            chunks: ['userManagement']
        }),
        new HtmlWebpackPlugin({
            filename: "roleManagement.html",
            template: "../src/scripts/pages/roleManagement/template.html",
            meta: {
                'viewport': 'width=device-width, initial-scale=1, shrink-to-fit=no'
            },
            chunks: ['roleManagement']
        }),
        new HtmlWebpackPlugin({
            filename: "menuManagement.html",
            template: "../src/scripts/pages/menuManagement/template.html",
            meta: {
                'viewport': 'width=device-width, initial-scale=1, shrink-to-fit=no'
            },
            chunks: ['menuManagement']
        })
    ]
}

webpack.dev.js

var merge = require('webpack-merge');
var commonConfig = require('./webpack.common');
var path = require("path");

const devConfig = {
    mode: "development",
    devtool: "cheap-module-eval-source-map",
    devServer: {
        publicPath: "/",
        contentBase: "../src/main/resources/static",
        filename: "[name].js",
        port: 8080
    }
};

module.exports = merge(commonConfig, devConfig);

webpack.prod.js:

var merge = require('webpack-merge');
var commonConfig = require('./webpack.common');
var path = require("path");

const prodConfig = {
    mode: "production",
    devtool: "cheap-module-source-map"
};

module.exports = merge(commonConfig, prodConfig);

其中,我用npm run dev是正常的,用npm run build的话,axios就不请求了, chrome控制台和webpack控制台都没有报错,

http://img1.sycdn.imooc.com/szimg/5dbba0ea09f3d99119200300.jpg

只是wepack控制台有一些警告:

WARNING in asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).
This can impact web performance.
Assets: 
  home.js (370 KiB)
  menuManagement.js (456 KiB)
  roleManagement.js (456 KiB)
  userManagement.js (456 KiB)

WARNING in entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance.
Entrypoints:
  home (370 KiB)
      home.js
  userManagement (456 KiB)
      userManagement.js
  roleManagement (456 KiB)
      roleManagement.js
  menuManagement (456 KiB)
      menuManagement.js


WARNING in webpack performance recommendations: 
You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application.
For more info visit https://webpack.js.org/guides/code-splitting/

我用的后端是Java,所以使用Tomcat部署的,把cnpm run build的代码编译到java项目,运行后台axios不发请求,如图:

http://img1.sycdn.imooc.com/szimg/5dbba1c6092654fb19200510.jpg

请老师帮我看看吧,谢谢!

ps:

  1. 附上加载当前用户和菜单的js代码:

import '../../../global/js/jQuery/jquery-vendor'
import axios from 'axios'
import 'bootstrap-notify'
import {myUI} from '../../../global/js/utils/common'

import sideNavCss from '../css/index.css'

import BScroll from 'better-scroll'

console.log(sideNavCss)

$(function () {
    //返回认证信息(如用户名)和进行权限控制
    axios.get('/authentication').then(function (value) {
        if (value.code === 0) {
            //显示用户名
            $('.userInfo .username').text(value.data.name)
            //显示电子邮箱
            axios.get('/user/name/' + value.data.name).then(result => {
                $('.userInfo .email').text(result.email)
            }).catch((reason) => {
                console.error(reason)
            });
            //显示菜单
            axios.get(`/menu/user/${value.data.name}/recursive`).then(result => {
                // console.log(result)
                let loadMenuRecursive = function (result) {
                    let ul = document.createElement('ul');

                    for (let i = 0; i < result.length; i++) {
                        let menu = result[i];

                        let li = document.createElement('li');

                        let link = document.createElement('a');
                        if (menu.url) {
                            link.href = menu.url;
                            //经理要求把/index页面隐藏了
                            if (menu.url === '/index') {
                                link.style.display = 'none';
                            }
                        } else {
                            link.href = 'javascript:void(0);';
                        }
                        if (location.pathname.startsWith(menu.url)) {
                            link.classList.add('active');
                        }
                        link.innerText = menu.name;

                        li.appendChild(link);

                        if (menu.children.length) {
                            let subMenu = loadMenuRecursive(menu.children);
                            li.appendChild(subMenu);
                        }
                        ul.appendChild(li);
                    }
                    return ul;
                }
                let allMenu = loadMenuRecursive(result);


                new Promise((resolve, reject) => {
                    try {
                        allMenu.classList.add('navigation', 'content');
                        document.querySelector(`.${sideNavCss.sideNav} .wrapper`).appendChild(allMenu);
                        resolve();
                    } catch (e) {
                        reject(e);
                    }
                }).then(() => {
                    let activeLink = $('.navigation.content li a.active');
                    activeLink.parentsUntil('.navigation.content').not('li').show('slow');
                    $('.navigation.content li a').click(function (evt) {
                        console.log($(this).parents('.navigation.content > li').siblings())
                        $(this).parents('.navigation.content > li').siblings('li').find('ul').hide('fast');
                        $(this).next('ul').show('slow');
                    });
                    let scroll = new BScroll(document.querySelector(`.${sideNavCss.sideNav} .wrapper`), {
                        mouseWheel: {
                            speed: 20,
                            invert: false,
                            easeTime: 300
                        }
                    })

                    window.addEventListener('resize', function (evt) {
                        scroll.refresh()
                    })
                }).catch(reason => {
                    console.error(reason)
                })
            }).catch(reason => {
                console.error(reason)
            })
        } else {
            myUI.notify(value.msg + value.data, 'danger');
        }
    }).catch(function (reason) {
        console.error(reason)
    });
});


写回答

1回答

Dell

2019-10-18

控制台也不报错?

0
9
他门说这就是人生
回复
Dell
谢谢Dell老师的好意,这是公司的代码,我不敢发啊,看来我只有用npm run dev了,谢谢啊
2019-11-11
共9条回复

从基础到实战 手把手带你掌握新版Webpack4.0

知识点+项目实例+原理讲解 全方位解析Webpack4新版本

3627 学习 · 1291 问题

查看课程