webpack 相关配置

10 篇文章 0 订阅
const webpack = require('webpack');
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const AntdDayjsWebpackPlugin = require('antd-dayjs-webpack-plugin');
const Dotenv = require('dotenv-webpack');

const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');

// 移动端适配
const autoprefixer = require('autoprefixer');
const pxtoviewport = require('postcss-px-to-viewport');

module.exports = {
    stats: {
        errors: true, // 显示错误
            warnings: true, // 显示警告

            // 模块相关
            modules: true, // 显示模块信息
            moduleTrace: true, // 显示模块的依赖关系
            providedExports: true, // 显示导出的内容
            usedExports: true, // 显示使用的导出

            // 块相关
            chunks: true, // 显示包块信息
            chunkGroups: true, // 显示包块组信息
            chunkModules: true, // 显示包块中的模块
            chunkOrigins: true, // 显示包块的来源

            // 资产相关
            assets: true, // 显示资产信息
            assetModules: true, // 显示资产模块信息

            // 入口相关
            entrypoints: true, // 显示入口点信息

            // 性能相关
            performance: true, // 显示性能提示

            // 其他
            colors: true, // 使用颜色显示输出
            logging: 'info', // 设置日志级别 (none, error, warn, info, log, verbose)

            // 自定义
            // 您可以使用正则表达式或字符串来自定义显示哪些模块、块等
            modulesSort: 'size',
            chunksSort: 'size',
            assetsSort: 'size',
            exclude: [/node_modules/],
            maxModules: 0, // 显示的最大模块数量 (0 = no limit)
            maxAssets: 0, // 显示的最大资产数量 (0 = no limit)
            
    },
    optimization: {
        minimizer: [
            // 压缩js
            new TerserPlugin({
                test: /\.(ts|tsx|js|jsx)$/,
                extractComments: true,
                parallel: true,
                cache: true
            })
        ],
        splitChunks: {
            cacheGroups: {
                vendors: {
                    //node_modules里的代码
                    test: /[\\/]node_modules[\\/]/,
                    chunks: 'all',
                    name: 'vendors', //chunks name
                    priority: 10, //优先级
                    enforce: true
                }
            }
        }
    },
    resolve: {
        extensions: ['.ts', '.tsx', '.js', '.jsx', '.css', '.less', '.json'],
        alias: {
            '@src': path.resolve(__dirname, '../src/'),
            '@assets': path.resolve(__dirname, '../src/assets/'),
            '@components': path.resolve(__dirname, '../src/components/'),
            '@utils': path.resolve(__dirname, '../src/utils/'),
            '@hooks': path.resolve(__dirname, '../src/hooks/'),
            '@servers': path.resolve(__dirname, '../src/servers/'),
            '@actions': path.resolve(__dirname, '../src/actions/'),
            '@pages': path.resolve(__dirname, '../src/pages/'),
            '@request': path.resolve(__dirname, '../src/request.js'),
            '@config': path.resolve(__dirname, '../src/config.js'),
            '@routeConfig': path.resolve(__dirname, '../src/routeConfig.jsx')
        }
    },
    module: {
        rules: [
            // {
            //     enforce: 'pre',
            //     test: /\.(ts|tsx|js|jsx)$/,
            //     exclude: /node_modules/,
            //     loader: 'eslint-loader',
            //     options: {
            //         cache: true,
            //         emitWarning: true,
            //         failOnError: true
            //     }
            // },
            {
                test: /\.(js|jsx|ts|tsx)$/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        // 引用您项目中的 Babel 配置文件
                        configFile: path.resolve(__dirname, '.babelrc')
                    }
                },
                exclude: /node_modules/
            },
            {
                test: /\.(css|less)$/,
                use: [
                    process.env.ENV_LWD == 'development'
                        ? { loader: 'style-loader' }
                        : MiniCssExtractPlugin.loader,
                    {
                        loader: 'css-loader',
                        options: {
                            importLoaders: 1
                        }
                    },
                    {
                        loader: 'postcss-loader',
                        options: {
                            plugins: [
                                autoprefixer(),
                                pxtoviewport({
                                    viewportWidth: 375,
                                    mediaQuery: false,
                                    selectorBlackList: ['ant-']
                                })
                            ]
                        }
                    },
                    {
                        loader: 'less-loader',
                        options: {
                            javascriptEnabled: true
                        }
                    }
                ]
            },
            {
                test: /\.(png|svg|jpg|gif|jpeg)$/,
                loader: 'file-loader',
                options: {
                    outputPath: './assets/images',
                    publicPath: 'assets/images/',
                    esModule: false
                }
            },
            {
                test: /\.(mp3)$/,
                loader: 'file-loader',
                options: {
                    outputPath: './assets/audio',
                    publicPath: 'assets/audio/',
                    esModule: false
                }
            },
            {
                test: /\.(woff|woff2|eot|ttf|otf)$/,
                loader: 'file-loader',
                options: {
                    esModule: false
                }
            }
        ]
    },
    plugins: {
        // 配置入口页面
        html: new HtmlWebpackPlugin({
            title: 'project',
            template: 'public/index.html',
            favicon: path.resolve('public/favicon.ico'),
            removeComments: true,
            collapseWhitespace: true,
            removeRedundantAttributes: true,
            useShortDoctype: true,
            removeEmptyAttributes: true,
            removeStyleLinkTypeAttributes: true,
            keepClosingSlash: true,
            minifyJS: true,
            minifyCSS: true,
            minifyURLs: true
        }),
        // 清理dist包
        cleanWebpack: new CleanWebpackPlugin(),
        // 抽取css
        miniCssExtract: new MiniCssExtractPlugin({
            filename:
                process.env.ENV_LWD == 'development' ? './css/[id].css' : './css/[id].[hash].css',
            chunkFilename:
                process.env.ENV_LWD == 'development' ? './css/[id].css' : './css/[id].[hash].css',
            ignoreOrder: true
        }),
        namedModules: new webpack.NamedModulesPlugin(),
        // 压缩css
        optimizeCssAssets: new OptimizeCssAssetsPlugin(),
        // 生成包依赖图
        bundleAnalyzer: new BundleAnalyzerPlugin({ analyzerPort: 8081 }),
        // 打包进度
        progressBarPlugin: new ProgressBarPlugin(),
        // 加载中文包
        ContextReplacementPlugin: new webpack.ContextReplacementPlugin(/moment\/locale$/, /zh-cn/),
        CompressionPlugin: new CompressionPlugin({
            filename: '[path].gz[query]',
            algorithm: 'gzip',
            test: /\.js$|\.css$|\.jsx$|\.less$|\.html$/,
            threshold: 10240,
            minRatio: 0.8
        }),
        AntdDayjsWebpackPlugin: new AntdDayjsWebpackPlugin({ preset: 'antdv3' }),
        DefinePlugin: new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify(process.env.ENV_LWD)
        }),
        CopyPlugin: new CopyPlugin([
            { from: './src/assets/js', to: '../dist/assets/js', toType: 'dir' }
        ]),
        HotModuleReplacementPlugin: new webpack.HotModuleReplacementPlugin(),
        dotnev: new Dotenv()
    },
    devServer: {
        contentBase: path.resolve(__dirname, 'dist'),
        hot: true,
        historyApiFallback: true,
        compress: true,
        host: '0.0.0.0',
        useLocalIp: true,
        https: false
    },
    watchOptions: {
        aggregateTimeout: 600
    },
    // externals 排除对应的包,注:排除掉的包必须要用script标签引入下
    externals: {}
};

2.Babel 相关的警告提示 (.babelrc文件)

{
  "presets": [
    "next/babel",
    [
      "@babel/preset-env",
      {
        "targets": [ ">0.2%",
        "not ie <= 99",
        "not android <= 4.4.4",
        "not dead",
        "not op_mini all"]
      }
    ]
  ],
  "plugins": [
    [
      "module-resolver",
      {
        "alias": {
          "~": "./src"
        }
      }
    ],
//警告提示
["@babel/plugin-proposal-class-properties", { "loose": true }],  
    ["@babel/plugin-proposal-private-methods", { "loose": true }],
    ["@babel/plugin-proposal-private-property-in-object", { "loose": true }]
    // "@babel/plugin-proposal-optional-chaining",
    // "@babel/plugin-proposal-nullish-coalescing-operator",
    // "@babel/plugin-proposal-private-property-in-object"
    
  ],
  "experimental": {
    "forceSwcTransforms": false
  }
}

3.确保您的 Babel 配置文件被 Webpack 正确加载和使用

module.exports = {
  // ... 其他 Webpack 配置
  module: {
    rules: [
      {
                test: /\.(js|jsx|ts|tsx)$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            },
    ]
  }
};

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
webpack的完整配置包括以下几个方面: 1. 安装webpackwebpack-cli:首先,你需要在项目中安装webpackwebpack-cli。你可以使用以下命令来安装它们:`npm install --save-dev webpack webpack-cli`。这样可以确保在项目中使用webpack。 2. 创建webpack配置文件:接下来,你需要创建一个名为`webpack.config.js`的文件,并在其中编写webpack配置。这个配置文件是一个JavaScript模块,它需要导出一个包含配置选项的对象。在这个配置文件中,你可以定义入口文件、输出文件、加载器和插件等。 3. 配置入口文件和输出文件:在webpack配置中,你需要指定一个或多个入口文件和一个输出文件。入口文件是你项目中的主要文件,它将作为webpack的起点。输出文件是webpack生成的打包文件,它将包含所有的模块和依赖关系。 4. 配置加载器和插件:webpack提供了丰富的加载器和插件,用于处理不同类型的文件和执行其他任务。加载器用于处理非JavaScript文件,比如将CSS转换为JavaScript模块,或者将ES6代码转换为ES5代码。插件可以用于执行额外的任务,比如压缩代码、提取公共模块或生成HTML文件。 5. 配置开发服务器和热模块替换:webpack还提供了开发服务器和热模块替换功能,以便在开发过程中实时预览和更新代码。你可以在配置中指定服务器的地址、端口和代理等选项,以及启用热模块替换。 6. 配置其他选项:除了上述内容之外,你还可以配置其它选项,比如优化输出、指定模块查找路径、设置环境变量等。 总结起来,webpack的完整配置包括安装webpackwebpack-cli、创建配置文件、配置入口文件和输出文件、配置加载器和插件、配置开发服务器和热模块替换,以及其他选项的配置。你可以根据你的项目需求和具体情况来编写和调整这些配置项。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值