webpack / webpack-dev-server

Serves a webpack app. Updates the browser on changes. Documentation https://webpack.js.org/configuration/dev-server/.
MIT License
7.8k stars 1.43k forks source link

webpack-dev-server DELETES THE WHOLE SUBTREE where it is ran after not finding the DirectoryWatcher module #2791

Closed davidkofman closed 3 years ago

davidkofman commented 3 years ago

Code

// webpack.config.js
/* global __dirname, process */

const webpack              = require('webpack');
const path                 = require('path');
const CopyWebpackPlugin    = require('copy-webpack-plugin');
const HtmlWebpackPlugin    = require('html-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const environmentsFile     = require('./environments.json');
const mocksFile            = require('./mocks.json');
const appPath              = path.join(__dirname, 'src');
const testPath             = path.join(__dirname, 'test');
const distDir              = 'build';
const distPath             = process.env.NODE_ENV === 'production' ? path.join(__dirname, distDir) : __dirname;

const mimic_enabled     = process.env.NODE_ENV === 'development';

const mocks             = mimic_enabled ? mocksFile : null;

const exclude           = /node_modules/;

const isGcpSkin         = process.env['CE_UI_TYPE'] === 'GCP';

process.traceDeprecation = true;

function getENVReplacements () {
    const replacements = environmentsFile[process.env.NODE_ENV];
    const result = {};

    Object.keys(replacements)
        .forEach((key) => result[key] = JSON.stringify(replacements[key]));

    result['$_IS_GCP_SKIN'] = isGcpSkin;
    result['$_GOOGLE_AUTH_CLIENT_ID'] = JSON.stringify(process.env['GOOGLE_AUTH_CLIENT_ID'] || '');
    result['$_RECAPTCHA_SITE_KEY'] = JSON.stringify(process.env['RECAPTCHA_SITE_KEY'] || '');

    if (mocks) {
        result['$_MOCKS'] = JSON.stringify(mocks);
    }
    else {
        result['$_MOCKS'] = null;
    }

    return result;
}

const config = {

    mode: (process.env.NODE_ENV === 'production')? 'production' : (process.env.NODE_ENV === 'development')? 'development' : 'none',

    // The base directory for resolving `entry` (must be absolute path)
    context: appPath,

    entry: {
        app: 'index.js',
        // vendor: [
        //  'babel-polyfill',
        //  'angular',
        //  '@angular/router/angular1/angular_1_router',
        //  'angular-sanitize',
        //  'angular-messages',
        //  'angular-cookies',
        //  'angular-material',
        //  'angular-material-data-table/dist/md-data-table',
        //  'angular-material-data-table/dist/md-data-table.css',
        //  'moment',
        //  'angular-moment',
        //  'md-date-range-picker'
        //  // 'angular-intercom-mini',
        // ]
    },

    output: {
        path: distPath,
        publicPath: '/',
        filename: 'bundle.[hash].js'
    },

    plugins: [
        // Global replacements for each environment
        new webpack.DefinePlugin(getENVReplacements()),

        new CopyWebpackPlugin({
            patterns: [
                {
                    from: `${appPath}/_assets/images`,
                    to: `${distPath}/_assets/images`,
                },
                {
                    from: `${appPath}/_assets/stylesheets/gcp-skin.css`,
                    to: `${distPath}/_assets/stylesheets/gcp-skin.css`,
                },
                {
                    from: `${appPath}/_assets/stylesheets/mimic-fix.css`,
                    to: `${distPath}/_assets/stylesheets/mimic-fix.css`,
                },
                {
                    from: `${appPath}/robots.txt`,
                    to: `${distPath}/robots.txt`,
                },
                {
                    from: `${appPath}/favicon.ico`,
                    to: `${distPath}/favicon.ico`,
                },
                {
                    from: `${appPath}/jquery.min.js`,
                    to: `${distPath}/jquery.min.js`,
                }
            ]
        }),

        // Generate index.html with included script tags
        new HtmlWebpackPlugin({
            inject: 'body',
            template: 'index.html',
            isGcpSkin: isGcpSkin,
            isProduction: (process.env.NODE_ENV === 'production'),
            mimicEnabled: (mimic_enabled)
        }),

        /*new HtmlWebpackPlugin({
         inject: 'body',
         filename: 'login.html',
         template: 'src/login.html',
         }),*/

        // Remove build related folders
        new CleanWebpackPlugin(),
    ],

    // Enable loading modules relatively (without the ../../ prefix)
    resolve: {
        modules: ['node_modules', appPath, testPath]
    },

    module: {
        rules: [

            // Transpile ES6 and annotate AngularJS dependencies
            {
                test: /\.js$/,
                use: [
                    // {
                    //  loader: 'ng-annotate-loader'
                    // },
                    {
                        loader: 'babel-loader',
                        options: {
                            presets: ['@babel/preset-env']
                        }
                    }
                ],
                exclude
            },

            // SCSS
            {
                test: /\.(css)$/,
                use: [
                    'style-loader',
                    'css-loader',
                    {
                        loader: 'postcss-loader',
                        options: {
                            postcssOptions: {
                                plugins: [
                                    [
                                        'postcss-preset-env',
                                    ]
                                ]
                            }
                        }
                    }
                ]
            },

            // JSON
            {
                test: /\.json$/,
                use: ['json'],
                exclude
            },

            // Allow `require`ing image/font files (also when included in CSS)
            // Inline assets under 5kb as Base64 data URI, otherwise uses `file-loader`
            {
                test: /\.(eot|woff2?|ttf|otf)(\?.*)?$/i,
                use: [
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 5120,
                            name: '[path][name].[hash].[ext]'
                        }
                    }
                ]
            },

            {
                test: /\.(jpe?g|png|gif|svg)(\?.*)?$/i,
                use: [
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 5120,
                            name: '[path][name].[hash].[ext]'
                        }
                    }
                ]
            },

            // Create AngularJS templates from HTMLs
            {
                test: /\.html$/,
                use: [
                    {
                        loader: 'html-loader',
                        options: {
                            minimize: true
                        }
                    }               ]
            }
        ]
    },

    // Settings for webpack-dev-server
    devServer: {
        contentBase: './app',
        hot: true,
        noInfo: true,
        inline: true,
        historyApiFallback: true,
        https: true,
        proxy: {
            '/api/**': {
                // target: 'https://example.cloudendure.info',
                target: 'https://' + process.env['DOMAIN'],
                secure: false,
                bypass: function(req, res, proxyOptions) {
                    if (req.options && req.options.download) {
                        console.log('Download requested. req url is:' + req.url);
                        return '/auditlog.csv';
                    }
                }
            }
        },
        headers: {
            'content-security-policy': "script-src 'self' 'unsafe-eval'  https://www.google-analytics.com https://apis.google.com/js https://www.google.com/recaptcha/ https://www.recaptcha.net/recaptcha/ https://www.gstatic.com/recaptcha/ https://a0.awsstatic.com/s_code/  https://amazonwebservices.d2.sc.omtrdc.net/;" +
                                       "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com/css; connect-src 'self'; font-src 'self' https://fonts.gstatic.com/; " +
                "frame-src https://www.google.com/recaptcha/ https://www.recaptcha.net/recaptcha/ https://www.youtube.com/embed/DYcuG7p5new https://www.youtube.com/embed/R9JDCRCro-s; form-action 'self'; frame-ancestors 'none'"
        }
    }
};
if ((mimic_enabled)) {
    config.resolve.alias = {
            mimic: 'mimic'
        };
}
else {
    config.resolve.alias = {
        mimic: path.join(__dirname, 'src', '_config', 'dummyMimic')
    };
}

if (process.env['CE_DEVELOPMENT'] || (process.env.NODE_ENV === 'development')) {
    console.log('Building with source maps');
    config.devtool = '#inline-source-map';
}
else {
    console.log('Building without source maps');
}

if (process.env.NODE_ENV !== 'test') {
    // config.plugins.push(
    //  new webpack.optimize.CommonsChunkPlugin(
    //      /* chunkName: */ 'vendor',
    //      /* filename: */ 'vendor.[hash].js'
    //  )
    // );
}

module.exports = config;
// additional code, remove if not needed.

I am running 'webpack serve' as follows (part of my package.json):

  "scripts": {
    "start": "NODE_ENV=development node $NODE_DEBUG_OPTION node_modules/.bin/webpack serve --color --hot --progress",
  }

Expected Behavior

webpack-dev-server runs with my app

Actual Behavior

webpack-dev-server fails when not finding the DirectoryWatcher module and wipes the whole subtree where it is ran:

f0189883f4bd:CEUserConsole kofmand$ npm start

CloudEndure_VV@1.0.0 start /Users/kofmand/dev/CloudEndure/CEUserConsole NODE_ENV=development node $NODE_DEBUG_OPTION node_modules/.bin/webpack serve --color --progress

Building with source maps 11% building 16/19 modules 3 active ...re/CEUserConsole/node_modules/webpack-dev-server/client/utils/getCurrentScriptSource.js(node:695) DeprecationWarning: loaderUtils.parseQuery() received a non-string value which can be problematic, see https://github.com/webpack/loader-utils/issues/56 parseQuery() will be replaced with getOptions() in the next major version of loader-utils. at Object.parseQuery (/Users/kofmand/dev/CloudEndure/CEUserConsole/node_modules/loader-utils/index.js:78:3) at Object.module.exports (/Users/kofmand/dev/CloudEndure/CEUserConsole/node_modules/html-loader/index.js:18:26) at LOADER_EXECUTION (/Users/kofmand/dev/CloudEndure/CEUserConsole/node_modules/loader-runner/lib/LoaderRunner.js:119:14) at runSyncOrAsync (/Users/kofmand/dev/CloudEndure/CEUserConsole/node_modules/loader-runner/lib/LoaderRunner.js:120:4) at iterateNormalLoaders (/Users/kofmand/dev/CloudEndure/CEUserConsole/node_modules/loader-runner/lib/LoaderRunner.js:232:2) at Array. (/Users/kofmand/dev/CloudEndure/CEUserConsole/node_modules/loader-runner/lib/LoaderRunner.js:205:4) at Storage.finished (/Users/kofmand/dev/CloudEndure/CEUserConsole/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:55:16) at provider (/Users/kofmand/dev/CloudEndure/CEUserConsole/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:91:9) at /Users/kofmand/dev/CloudEndure/CEUserConsole/node_modules/graceful-fs/graceful-fs.js:123:16 at FSReqWrap.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:53:3) [webpack-cli] Uncaught exception: Error: Cannot find module './DirectoryWatcher' [webpack-cli] Error: Cannot find module './DirectoryWatcher' at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15) at Function.Module._load (internal/modules/cjs/loader.js:562:25) at Module.require (internal/modules/cjs/loader.js:690:17) at require (/Users/kofmand/dev/CloudEndure/CEUserConsole/node_modules/v8-compile-cache/v8-compile-cache.js:161:20) at WatcherManager.getDirectoryWatcher (/Users/kofmand/dev/CloudEndure/CEUserConsole/node_modules/watchpack/lib/watcherManager.js:14:25) at WatcherManager.watchFile (/Users/kofmand/dev/CloudEndure/CEUserConsole/node_modules/watchpack/lib/watcherManager.js:28:14) at Watchpack. (/Users/kofmand/dev/CloudEndure/CEUserConsole/node_modules/watchpack/lib/watchpack.js:38:49) at Array.map () at Watchpack.watch (/Users/kofmand/dev/CloudEndure/CEUserConsole/node_modules/watchpack/lib/watchpack.js:37:28) at NodeWatchFileSystem.watch (/Users/kofmand/dev/CloudEndure/CEUserConsole/node_modules/webpack/lib/node/NodeWatchFileSystem.js:70:16) f0189883f4bd:CEUserConsole kofmand$ ls f0189883f4bd:CEUserConsole kofmand$ git status On branch david_update_packages Your branch is ahead of 'origin/david_update_packages' by 57 commits. (use "git push" to publish your local commits)

Changes not staged for commit: (use "git add/rm ..." to update what will be committed) (use "git checkout -- ..." to discard changes in working directory)

deleted:    .gitignore
deleted:    .npmrc
deleted:    README.md
deleted:    app/auditlog.csv
deleted:    build.xml
deleted:    environments.json
deleted:    karma.conf.js
deleted:    mocks.json
deleted:    package-lock.json
deleted:    package.json
deleted:    src/_assets/fonts/.gitkeep
deleted:    src/_assets/images/.gitkeep

etc.

For Bugs; How can we reproduce the behavior?

for me it happens when I run webpack serve with the specified versions.

For Features; What is the motivation and/or use-case for the feature?

alexander-akait commented 3 years ago

we don't remove files and I can't reproducible, sorry your issue is not readable

davidkofman commented 3 years ago

we don't remove files and I can't reproducible, sorry your issue is not readable

@evilebottnawi I guess you mean we don't remove files on purpose, that's the nature of bugs - they happen without you wanting them. What exactly is not readable? Isn't deleting all the source files worth investigating a little? As for reproduce I'd start by removing the DirectoryWatcher and seeing what happens.

alexander-akait commented 3 years ago

What exactly is not readable? Isn't deleting all the source files worth investigating a little?

We don't have code for removing files

As for reproduce I'd start by removing the DirectoryWatcher and seeing what happens.

You have problems with plugins

Don't ignore For Bugs; How can we reproduce the behavior?

davidkofman commented 3 years ago

You have problems with plugins

I installed webpack 4.44.2 which installed watchpack 1.7.4 as a dependency. watchpack/lib/watcherManager.js has require("./DirectoryWatcher") but does not include this module. So how come I have a problem?

Don't ignore For Bugs; How can we reproduce the behavior?

added

alexander-akait commented 3 years ago

webpack-dev-server can't wok without this file

alexander-akait commented 3 years ago

I think you have two version of webpack, double check it

davidkofman commented 3 years ago

I think you have two version of webpack, double check it

image

I don't have a global installation of webpack

alexander-akait commented 3 years ago

Why you remove DirectoryWatcher?

davidkofman commented 3 years ago

Why you remove DirectoryWatcher?

I don't, that's the thing!! It happens when I run webpack serve

alexander-akait commented 3 years ago

I don't understand the problem, please provide how I can reproducible it