首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >忽略了Webpack DLL

忽略了Webpack DLL
EN

Stack Overflow用户
提问于 2021-08-18 17:23:20
回答 1查看 23关注 0票数 0

我一直在尝试在webpack4配置上设置DllPlugin,但无论我如何尝试,dll都会被忽略,包中也包含所有的供应商代码。

生成了vendor-manifest.json,但是它在主要的webpack配置中什么也不做。

以下是配置文件:

代码语言:javascript
复制
// webpack.vendor.config.js
'use strict';
var webpack = require('webpack')
var MomentLocalesPlugin = require('moment-locales-webpack-plugin');
var MiniCssExtractPlugin = require("mini-css-extract-plugin");
const path = require('path');
const libs = [
    "@peopleweek/react-org-chart",
    "classnames",
    "currency-formatter",
    "draft-js",
    "draftjs-to-html",
    "font-awesome-filetypes",
    "get-value",
    "has-value",
    "history",
    "html-to-draftjs",
    "i18n-iso-countries",
    "immutable",
    "interactjs",
    "json-form-data",
    "jsondiffpatch",
    "lodash",
    "memoize-one",
    "moment",
    "moment-timezone",
    "normalizr",
    "object-hash",
    "object.assign",
    "promise-polyfill",
    "prop-types",
    "query-string",
    "react",
    "react-autosuggest",
    "react-avatar-editor",
    "react-beautiful-dnd",
    "react-big-calendar",
    "react-bootstrap",
    "react-calendar-timeline",
    "react-color",
    "react-d3",
    "react-dates",
    "react-datetime",
    "react-dom",
    "react-draft-wysiwyg",
    "react-dropzone",
    "react-geosuggest",
    "react-google-recaptcha",
    "react-infinite-scroller",
    "react-linkify",
    "react-moment",
    "react-moment-proptypes",
    "react-number-format",
    "react-redux",
    "react-resize-to-aspect-ratio",
    "react-responsive",
    "react-responsive-tabs",
    "react-router-dom",
    "react-select",
    "react-share",
    "react-tether",
    "react-toastify",
    "react-url-query",
    "react-visjs-timeline",
    "recharts",
    "redux",
    "redux-socket.io",
    "redux-thunk",
    "set-value",
    "socket.io-client",
    "sugarss",
    "tz-ids",
    "vis",
    "whatwg-fetch",
];
module.exports = {
    mode: 'development',
    entry: {
        vendor: libs
    },
    output: {
        filename: 'vendor.bundle.js',
        path: path.join(__dirname, 'dist'),
        library: 'vendor_lib'
    },
    plugins: [
        new MomentLocalesPlugin({
            localesToKeep: ['fr', 'it', 'de', 'es', 'pt'],
        }),
        new MiniCssExtractPlugin({
            // Options similar to the same options in webpackOptions.output
            // both options are optional
            filename: '[name].css',
            chunkFilename: '[id].css',
        }),
        new webpack.DllPlugin({
            name: 'vendor_lib',
            path: path.join(__dirname, 'dist', 'vendor-manifest.json')
        }),
    ],
    module: {
        rules: [
            /**
             * Compiles ES6 and ES7 into ES5 code
             * Reference: https://github.com/babel/babel-loader
             */
            {
                test: /\.jsx?$/i,
                loader: 'babel-loader?cacheDirectory=true',
                exclude: /node_modules/,
                options: {}
            },
            /**
             * Compile SASS to CSS, then use same rules
             * Reference: https://github.com/webpack-contrib/sass-loader
             */
            {
                test: /\.scss$/i,
                loader: 'sass-loader',
                enforce: 'pre'
            },

            {
                test: /\.(sa|sc|c)ss$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                ],
            }
        ]
    }
}
代码语言:javascript
复制
'use strict';

var webpack = require('webpack');
var path = require('path');
var fs = require('fs');
var AssetsPlugin = require('assets-webpack-plugin');
var ExtractFilePlugin = require('extract-file-loader/Plugin');
var DashboardPlugin = require('webpack-dashboard/plugin');
var MomentLocalesPlugin = require('moment-locales-webpack-plugin');
var MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = function makeWebpackConfig(options) {
    /**
     * Whether we are running in dev-server mode (versus simple compile)
     */
    var DEV_SERVER = process.env.WEBPACK_MODE === 'watch';

    var mode = DEV_SERVER ? 'development' : 'production';

    var tenant = options.parameters.APP_ENV.indexOf('tenant_') === 0 ? options.parameters.APP_ENV.substr(7) : null;

    /**
     * Whether we are running inside webpack-dashboard
     */
    var DASHBOARD = process.env.WEBPACK_DASHBOARD === 'enabled';

    var publicPath;
    if (options.parameters.dev_server_public_path && DEV_SERVER) {
        publicPath = options.parameters.dev_server_public_path;

    } else if (options.parameters.public_path) {
        publicPath = options.parameters.public_path;
    } else {
        publicPath = DEV_SERVER ? '//localhost:8080/compiled/' : '/compiled/';
    }


    var tenantStylesVariablesPath = path.resolve(__dirname, 'app/Resources/assets/tenant/styles/_variables.scss');

    if (tenant) {
        var temp = tenant ? path.resolve(__dirname, 'app/config/tenants',  tenant ,'/styles/_variables.scss') : null;
        if (fs.existsSync(temp)) {
            tenantStylesVariablesPath = temp;
        }
    }

    /**
     * Config
     * Reference: https://webpack.js.org/concepts/
     * This is the object where all configuration gets set
     */
    var config = {
        entry: options.entry,
        mode: mode,
        resolve: {
            alias: Object.assign({}, options.alias, {
                '@tenant-styles-variables': tenantStylesVariablesPath
            }),
            extensions: ['.js', '.jsx'],
        },
        optimization: Object.assign({
            minimize: false,
            // splitChunks: {
            //     cacheGroups: {
            //         commons: {
            //             test: /[\\/]node_modules[\\/]/,
            //             name: 'vendors',
            //             chunks: 'all'
            //         }
            //     }
            // }
        }, DEV_SERVER ? {
            removeAvailableModules: false,
            removeEmptyChunks: false,
        }: {}),
        output: Object.assign({
            // Absolute output directory
            path: options.parameters.path ? options.parameters.path : path.resolve(__dirname, '/web/compiled/'),

            // Output path from the view of the page
            publicPath: publicPath,

            // Filename for entry points
            // Only adds hash in build mode
            filename: DEV_SERVER ? '[name].bundle.js' : '[name].[chunkhash].js',

            // Filename for non-entry points
            // Only adds hash in build mode
            chunkFilename: DEV_SERVER ? '[name].bundle.js' : '[name].[chunkhash].js',
        }, DEV_SERVER ? {
            // dev serveer only options
            pathinfo: false
        } : {}),

        /**
         * Options for webpack-dev-server.
         * Enables overlay inside the page if any error occurs when compiling.
         * Enables CORS headers to allow hot reload from other domain / port.
         * Reference: https://webpack.js.org/configuration/dev-server/
         */
        devServer: Object.assign({
            overlay: {
                warnings: false,
                errors: true
            },
            disableHostCheck: true,
            headers: {"Access-Control-Allow-Origin": "*"}
        }, options.parameters.dev_server || {})
    };


    /**
     * Loaders
     * Reference: https://webpack.js.org/concepts/loaders/
     * List: https://webpack.js.org/loaders/
     * This handles most of the magic responsible for converting modules
     */
    config.module = {
        rules: [
            /**
             * Compiles ES6 and ES7 into ES5 code
             * Reference: https://github.com/babel/babel-loader
             */
            {
                test: /\.jsx?$/i,
                loader: 'babel-loader?cacheDirectory=true',
                exclude: /node_modules/,
                options: {}
            },
            /**
             * Copy files to output directory
             * Rename the file using the asset hash
             * Pass along the updated reference to your code
             *
             * Reference: https://github.com/webpack/file-loader
             *
             * Query string is needed for URLs inside css files, like bootstrap
             * Overwrites name parameter to put original name in the destination filename, too
             */
            {
                test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)(\?.*)?$/i,
                loader: 'file-loader',
                options: {
                    name: '[name].[hash].[ext]'
                }
            },

            /**
             * Loads HTML files as strings inside JavaScript - can be used for templates
             *
             * Reference: https://github.com/webpack/raw-loader
             */
            {
                test: /\.html$/i,
                loader: 'raw-loader'
            },

            /**
             * Compile SASS to CSS, then use same rules
             * Reference: https://github.com/webpack-contrib/sass-loader
             */
            {
                test: /\.scss$/i,
                loader: ['sass-loader'],
                enforce: 'pre'
            },

            {
                test: /\.(sa|sc|c)ss$/,
                use: DEV_SERVER ? [
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                ] : [
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                    'postcss-loader',
                ],
            }
        ]
    };

    if (!DEV_SERVER) {
        config.module.rules.push(
            /**
             * Minify PNG, JPEG, GIF and SVG images with imagemin
             * Reference: https://github.com/tcoopman/image-webpack-loader
             *
             * See `config.imageWebpackLoader` for configuration options
             *
             * Query string is needed for URLs inside css files, like bootstrap
             */
            {
                test: /\.(gif|png|jpe?g)(\?.*)?$/i,
                enforce: 'pre',
                loader: 'image-webpack-loader',
                options: options.parameters.image_loader_options || {
                    optipng: {
                        optimizationLevel: 7,
                        progressive: true
                    }
                }
            }
        )

    }

    /**
     * Plugins
     * Reference: https://webpack.js.org/configuration/plugins/
     * List: https://webpack.js.org/plugins/
     */
    config.plugins = [
        new webpack.DllReferencePlugin({
            // context: __dirname,
            manifest: require('./dist/vendor-manifest.json'),
            // manifest: path.join(__dirname, 'build', 'vendor-manifest.json')
        }),
        // // To strip all locales except the ones supported
        // // (“en” is built into Moment and can’t be removed)
        // new MomentLocalesPlugin({
        //     localesToKeep: ['fr', 'it', 'de', 'es', 'pt'],
        // }),

        new MiniCssExtractPlugin({
            // Options similar to the same options in webpackOptions.output
            // both options are optional
            filename: DEV_SERVER ? '[name].css' : '[name].[hash].css',
            chunkFilename: DEV_SERVER ? '[id].css' : '[id].[hash].css',
        }),

        /**
         * Webpack plugin that emits a json file with assets paths - used by the bundle
         * Reference: https://github.com/kossnocorp/assets-webpack-plugin
         */
        new AssetsPlugin({
            filename: path.basename(options.manifest_path),
            path: path.dirname(options.manifest_path)
        }),

        /**
         * Adds assets loaded with extract-file-loader as chunk fies to be available in generated manifest
         * Used by the bundle to use binary files (like images) as entry-points
         * Reference: https://github.com/mariusbalcytis/extract-file-loader
         */
        new ExtractFilePlugin(),
        new webpack.EnvironmentPlugin({
            NODE_ENV: DEV_SERVER ? 'development' : 'production',
            DEBUG: DEV_SERVER
        })
    ];

    /**
     * Adds CLI dashboard when compiling assets instead of the standard output
     * Reference: https://github.com/FormidableLabs/webpack-dashboard
     */
    if (DASHBOARD) {
        config.plugins.push(new DashboardPlugin());
    }

    /**
     * Devtool - type of sourcemap to use per build type
     * Reference: https://webpack.js.org/configuration/devtool/
     */
    if (DEV_SERVER) {
        config.devtool = 'eval';
    } else {
        config.devtool = 'none';
    }

    console.log(config.plugins[0]);
    return config;
};

我试着寻找答案,但所有示例配置看起来都与我们的一模一样。显然,这里的主要配置比大多数示例更复杂,但主要部分与我见过的所有示例几乎是1:1。

EN

回答 1

Stack Overflow用户

发布于 2021-08-19 15:21:52

我终于找到了解决方案。由于某种原因,虽然我在文档中找不到它,但我必须指定它的名称。

代码语言:javascript
复制
new webpack.DllReferencePlugin({
     context: __dirname,
     manifest: require('./dist/vendor-manifest.json'),
     name: 'vendor_lib'
}) 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68836838

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档