zoukankan      html  css  js  c++  java
  • webpack(构建一个前端项目)详解--升级

    升级一个正式的项目结构

    分离webpack.config.js文件:
    新建一个webpack.config.base.js任何环境依赖的wbpack

    //public webpack 
    const path = require('path');
    
    const config = {
      target: 'web',
      entry: path.join(__dirname, '../src/index.js'),
      output: {
        filename: 'bundle.[hash:8].js',
        path: path.join(__dirname, '../dist')
      },
      module: {
        rules: [
          {
            test: /.vue$/,
            loader: 'vue-loader'
          },
          {
            test: /.jsx$/,
            loader: 'babel-loader'
          },
            {
                test: /.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/ //node_modules忽略掉
            },
            {
            test: /.(gif|jpg|jpeg|png|svg)$/,
            use: [
              {
                loader: 'url-loader',
                options: {
                  limit: 1024,
                  name: '/resource/[path][name].[hash:8].[ext]'//静态文件打包在资源文件下
                }
              }
            ]
          }
        ]
      }
    }
    
    module.exports = config
    
    

    新建webpack.config.client.js他是依赖于webpack.config.base.js,利用webpack-merge工具扩展配置文件。合并各种webpack配置文件。根据webpack里面的各个项合理的合并webpack.config文件。
    安装:npm install webpack-merge -D
    .json:文件中的dependencies中只放vue的版本,其余版本放在devDependencies

    const path = require('path');
    const HTMLPlugin = require('html-webpack-plugin');
    const webpack = require('webpack');
    const ExtractPlugin = require('extract-text-webpack-plugin');//单独打包css文件的插件
    const merge = require("webpack-merge");
    const baseConfig = require("./webpack.config.base");
    const isDev = process.env.NODE_ENV === 'development';
    
    let config;
    const defaultPlugins = [
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: isDev ? '"development"' : '"production"'
            }
        }),
        new HTMLPlugin()
    ];
    const devServer = {
        port: 8099,
        host: '0.0.0.0',
        overlay: {
            errors: true,
        },
        hot: true
    };
    
    if (isDev) {
        config = merge(baseConfig,{//合并到baseConfig文件中
            devtool: '#cheap-module-eval-source-map',
            module: {
                rules: [
                    {
                        test: /.styl/,
                        use: [
                            'style-loader',
                            'css-loader',
                            {
                                loader: 'postcss-loader',
                                options: {
                                    sourceMap: true,
                                }
                            },
                            'stylus-loader'
                        ]
                    }
                ]
            },
            devServer,
            plugins: defaultPlugins.concat([
                new webpack.HotModuleReplacementPlugin(),
                new webpack.NoEmitOnErrorsPlugin()
            ])
        });
    } else {
        config = merge(baseConfig,{
            entry: {
                app: path.join(__dirname, '../src/index.js'),
                vendor: ['vue']
            },
            output:{
                filename: '[name].[chunkhash:8].js'
            },
            module: {
                rules: [
                    {
                        test: /.styl/,
                        use: ExtractPlugin.extract({
                            fallback: 'style-loader',
                            use: [
                                'css-loader',
                                {
                                    loader: 'postcss-loader',
                                    options: {
                                        sourceMap: true,
                                    }
                                },
                                'stylus-loader'
                            ]
                        })
                    }        
                ]
            },
            plugins: defaultPlugins.concat([
                new ExtractPlugin('styles.[contentHash:8].css'),
                new webpack.optimize.CommonsChunkPlugin({
                    name: 'vendor'
                }),
                new webpack.optimize.CommonsChunkPlugin({
                    name: 'runtime'
                })
            ])
        });
    }
    
    module.exports = config
    
    

    修改json文件:

    "build": "cross-env NODE_ENV=production webpack --config build/webpack.config.client.js",
    "dev": "cross-env NODE_ENV=development webpack-dev-server --config build/webpack.config.client.js"
    

    vue-loader的配置

    在build文件下新建vue-loader.config.js
    传入环境的判断,暴露出去一个对象,vue-loader相关的配置

    preserveWhitepace: true,消除文本中的空格
    extractCSS: true,//vue组件中的css打包到单独的文件中
    cssModules: {},
    hotReload: false,//默认情况下是在production的情况下关闭热重载,不必设置
    
    //以下不怎常用:
    定义全局的的loader
    const docLoader = require.resolve("./doc-loader");
    loaders: {
        "docs": docLoader,
        js: "coffe-loader"//指定了loader会根据相应的loader去解析它
    },//自定义模块,
    preLoader: {
        //...
    },//先解析哪一种loader
    psotLoader: {
        //...
    }
    
    
    //使用时添加在摸个组件中 
    <docs>
        //...构建组件库的时候,给每一个组件写文档
    </docs>
    
    module.exports = (isDev) => {
        return {
            preserveWhitepace: true,
            extractCSS: true
            //这个实在线上环境是使用的所以开发版本不适用
            extractCSS: isDev
        }
    }
    

    在base.js中引入使用,修改rules下.vue-loader

    const createVueLoaderOptions = require("./vue-loader.config");
    const isDev = process.env.NODE_ENV === 'development';
    
         {
            test: /.vue$/,
            loader: 'vue-loader',
            options: createVueLoaderOptions(isDev)
          },
    

    css的热跟新

    默认的css是没有热更新的,要安装vue-style-loader

    npm install vue-style-loader -D
    

    安装了之后修改webpack.congif.js文件中的style-loader

    打包之前删除上一次打包的文件

    安装rimraf每次打包之前删除打包的上一个版本

    npm install rimraf -D
    

    在json文件中添加clear

    "scripts": {
        "test": "echo "Error: no test specified" && exit 1",
        "build:client": "cross-env NODE_ENV=production webpack --config build/webpack.config.client.js",
        "build": "npm run clean && npm run build:client",
        "clean": "rimraf dist",//删除文件
        "dev": "cross-env NODE_ENV=development webpack-dev-server --config build/webpack.config.client.js"
      }
    

    cssModule的配置:

    cssModules: {
        localIdentName: "[path]-[name]-[hash:base64:5]"
        //线上的可以省略路径,name
        localIdentName: "[hash:base64:5]"
        localIdentName: isDev ? "[path]-[name]-[hash:base64:5]" : "[hash:base64:5]"
        //把css对应的类名,根据路径,文件名,文件内容的hsah生成一个独一无二的类名,调用是别的文件无法使用。
        camelCase: teue//js命名方式,把css中带中划线的转换成驼峰命名。给使用的style标签添加module属性,原有css类修改:class="$style.mainHeader"
    
        //外部css的使用:
        在css-loader中配置,把css-loader变成一个对象
        {
            loader: "css-loader",
            options: {
                module: true,
                localIdentName: isDev ? "[path]-[name]-[hash:base64:5]" : "[hash:base64:5]"
            }
        }
    
        import className from "../../xx.styl";
    
        <div id="className.xxx"></div>
    }
    

    selint

    防止代码低级出错,团队协作统一性。使用eslint-config-standard的规范,它有依赖了很多的包
    安装:

    npm install eslint eslint-config-standard eslint-plugin-standard eslint-plugin-promise eslint-plugin-import eslint-plugin-node -D
    

    在项目文件下创建.eslintrc文件:

    {
        "extends": "standard",//使用标准规则
        //使用之后用eslint校验代码,但没有办法识html中js的代码,安装eslint-plugin-html -D识别html中的js代码
        "plugins": [
            "html"
        ],
        //在json中配置script
        "parser": "babel-eslint"//babel处理
    }
    
    "script": {
        "lint": "eslint --ext .js .jsx .vue client/",
        "lint-fix": "eslint --fix --ext .js .jsx .vue client/",
        //fix自动修复
        //每次修改代码会自动检查。安装eslint-loader babel-eslint -D添加parser属性在base.js中配置loader在rules中添加对象:
        {
            test: /.(vue|js|jsx)$/,
            loader: "eslint-loader",
            esclude: /node_modules/,
            enforce: "pre"//预处理,以上文件在使用vue-loader加载之前都会通过eslint-loader检测,post之后预处理。
        }
    }
    

    editorConfig规范编辑器的配置

    编译器插件,在编译器插件中自行安装
    新建editorConfig,在不同的编辑器安装此插件,让不同的编辑器在使用这个项目编辑的时候使用相同的配置。

    root = true//都当这个文件就行,不用往上层读
    [*]//所有的文件规定规范
    charset = utf-8
    end_of_line = lf
    indent_size = 2
    index_style = space
    insert_final_newline = true//保存文件末尾自动添加空行,eslint规范每个页面最后一行为空行 
    trim_trailing_whitespace = true//去掉多余的空格
    
    

    precommit检测代码

    git提交时,使用precommit插件,如果代码检查不符合eslint不能提交。git commit时自动调用precommit,检测代码。不通过,无法提交。
    安装:husky包

    npm install husky -D
    

    会自动在项目文件下生成.githock文件,读取config文件中的内容,在srcipt添加脚本。

    "precommit": "npm run lint-fix"
    

    webpack的升级

    卸载所有相关webpack及插件。

    npm uninstall webpack webpack-dev-server webpack-merge -D
    

    安装即可:

    npm install webpack webpack-dev-server webpack-merge webpack-cli
    

    webpack-cli 4以上在命令行启动的部分脚本在webpack-cli上。
    其他的包也是卸载安装升级
    @next没有发布的下一个包
    修改配置:在base中添加mode

    const config = {
        mode: process.env.NODE_ENV || "production ",//development || "production",
        
    }
    

    client.js中修改,删掉CommonChunkPlugin

    optimization: {
        splitChunks: {
            chunks: "all"//删除vender
        },
        runtimeChunk: true
    }
    //开发时的配置:
    devtool
    new webpack.NoEmitOnErrorsPlugin()
    删除 
    
  • 相关阅读:
    加载第三方Cocoapod库时到项目时
    IOS seachbar 收回键盘
    设置tableView 的Section的title问题
    UISearchView
    UICollectionView 头视图、 尾视图以及Cell自定制
    UICollectionView
    Tomcat上java.lang.IllegalStateException: Optional int parameter 'id' is not present
    格式化p6spy的输出日志
    bootstrap fileinput添加上传成功回调事件
    条件注释判断浏览器<!--[if !IE]>
  • 原文地址:https://www.cnblogs.com/intelwisd/p/8868407.html
Copyright © 2011-2022 走看看