Skip to content
This repository was archived by the owner on Aug 7, 2021. It is now read-only.

Cannot find module 'webpack-bundle-analyzer' #693

Closed
1 task
anuragd7 opened this issue Oct 15, 2018 · 3 comments
Closed
1 task

Cannot find module 'webpack-bundle-analyzer' #693

anuragd7 opened this issue Oct 15, 2018 · 3 comments
Labels

Comments

@anuragd7
Copy link

Environment
Provide version numbers for the following components (information can be retrieved by running tns info in your project folder or by inspecting the package.json of the project):

  • CLI: 4.2.4

  • Please, attach your package.json and webpack.config.js as these configurations are usually critical for investigating issues with webpack

PACKAGE.JSON
{
  "android": {
    "markingMode": "none"
  },
  "description": "NativeScript Application",
  "license": "SEE LICENSE IN <your-license-filename>",
  "readme": "NativeScript Application",
  "repository": "<fill-your-repository-here>",
  "nativescript": {
    "id": "org.nativescript.xyz",
    "tns-android": {
      "version": "4.2.0"
    },
    "tns-ios": {
      "version": "4.2.0"
    }
  },
  "dependencies": {
    "@angular/animations": "~6.1.0",
    "@angular/common": "~6.1.0",
    "@angular/compiler": "~6.1.0",
    "@angular/core": "~6.1.0",
    "@angular/forms": "~6.1.0",
    "@angular/http": "~6.1.0",
    "@angular/platform-browser": "~6.1.0",
    "@angular/platform-browser-dynamic": "~6.1.0",
    "@angular/router": "~6.1.0",
    "nativescript-algolia": "^1.1.0",
    "nativescript-angular": "^6.1.0",
    "nativescript-camera": "^4.0.2",
    "nativescript-email": "^1.5.3",
    "nativescript-filter-select": "^1.2.9",
    "nativescript-filterable-listpicker": "^2.2.3",
    "nativescript-geolocation": "^4.2.6",
    "nativescript-imagepicker": "^6.0.4",
    "nativescript-iqkeyboardmanager": "^1.3.0",
    "nativescript-ngx-slides": "^6.1.0",
    "nativescript-pdf-view": "^2.0.1",
    "nativescript-plugin-firebase": "^6.5.0",
    "nativescript-social-share": "^1.5.0",
    "nativescript-theme-core": "~1.0.4",
    "nativescript-toast": "^1.4.6",
    "nativescript-ui-listview": "^3.7.1",
    "nativescript-web-image-cache": "^4.2.2",
    "reflect-metadata": "~0.1.8",
    "rxjs": "^6.0.0",
    "rxjs-compat": "^6.2.2",
    "tns-core-modules": "^4.2.1"
  },
  "devDependencies": {
    "@angular/compiler-cli": "~6.1.0",
    "@ngtools/webpack": "~6.2.0",
    "babel-traverse": "6.26.0",
    "babel-types": "6.26.0",
    "babylon": "6.18.0",
    "codelyzer": "^4.4.4",
    "es6-promise-loader": "^1.0.2",
    "lazy": "1.0.11",
    "nativescript-dev-typescript": "^0.7.3",
    "nativescript-dev-webpack": "^0.16.2",
    "prettier": "^1.11.1",
    "tslint": "^5.1.0",
    "typescript": "~2.7.2",
    "webpack": "^4.20.2",
    "webpack-cli": "^3.1.2",
    "zone.js": "^0.8.26"
  },
}

webpack.config.js

const { join, relative, resolve, sep } = require("path");

const webpack = require("webpack");
const nsWebpack = require("nativescript-dev-webpack");
const nativescriptTarget = require("nativescript-dev-webpack/nativescript-target");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");
const { NativeScriptWorkerPlugin } = require("nativescript-worker-loader/NativeScriptWorkerPlugin");
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const { AngularCompilerPlugin } = require("@ngtools/webpack");

module.exports = env => {
    // Add your custom Activities, Services and other Android app components here.
    const appComponents = [
        "tns-core-modules/ui/frame",
        "tns-core-modules/ui/frame/activity",
    ];

    const platform = env && (env.android && "android" || env.ios && "ios");
    if (!platform) {
        throw new Error("You need to provide a target platform!");
    }

    const projectRoot = __dirname;

    // Default destination inside platforms/<platform>/...
    const dist = resolve(projectRoot, nsWebpack.getAppPath(platform, projectRoot));
    const appResourcesPlatformDir = platform === "android" ? "Android" : "iOS";

    const {
        // The 'appPath' and 'appResourcesPath' values are fetched from
        // the nsconfig.json configuration file
        // when bundling with `tns run android|ios --bundle`.
        appPath = "app",
        appResourcesPath = "app/App_Resources",

        // You can provide the following flags when running 'tns run android|ios'
        aot, // --env.aot
        snapshot, // --env.snapshot
        uglify, // --env.uglify
        report, // --env.report
        sourceMap, // --env.sourceMap
    } = env;

    const appFullPath = resolve(projectRoot, appPath);
    const appResourcesFullPath = resolve(projectRoot, appResourcesPath);

    const entryModule = aot ?
        nsWebpack.getAotEntryModule(appFullPath) : 
        `${nsWebpack.getEntryModule(appFullPath)}.ts`;
    const entryPath = `.${sep}${entryModule}`;

    const config = {
        mode: uglify ? "production" : "development",
        context: appFullPath,
        watchOptions: {
            ignored: [
                appResourcesFullPath,
                // Don't watch hidden files
                "**/.*",
            ]
        },
        target: nativescriptTarget,
        entry: {
            bundle: entryPath,
        },
        output: {
            pathinfo: false,
            path: dist,
            libraryTarget: "commonjs2",
            filename: "[name].js",
            globalObject: "global",
        },
        resolve: {
            extensions: [".ts", ".js", ".scss", ".css"],
            // Resolve {N} system modules from tns-core-modules
            modules: [
                resolve(__dirname, "node_modules/tns-core-modules"),
                resolve(__dirname, "node_modules"),
                "node_modules/tns-core-modules",
                "node_modules",
            ],
            alias: {
                '~': appFullPath
            },
            symlinks: true
        },
        resolveLoader: {
            symlinks: false
        },
        node: {
            // Disable node shims that conflict with NativeScript
            "http": false,
            "timers": false,
            "setImmediate": false,
            "fs": "empty",
            "__dirname": false,
        },
        devtool: sourceMap ? "inline-source-map" : "none",
        optimization: {
            splitChunks: {
                cacheGroups: {
                    vendor: {
                        name: "vendor",
                        chunks: "all",
                        test: (module, chunks) => {
                            const moduleName = module.nameForCondition ? module.nameForCondition() : '';
                            return /[\\/]node_modules[\\/]/.test(moduleName) ||
                                    appComponents.some(comp => comp === moduleName);
                        },
                        enforce: true,
                    },
                }
            },
            minimize: !!uglify,
            minimizer: [
                new UglifyJsPlugin({
                    uglifyOptions: {
                        parallel: true,
                        cache: true,
                        output: {
                            comments: false,
                        },
                        compress: {
                            // The Android SBG has problems parsing the output
                            // when these options are enabled
                            'collapse_vars': platform !== "android",
                            sequences: platform !== "android",
                        }
                    }
                })
            ],
        },
        module: {
            rules: [
                {
                    test: new RegExp(entryPath),
                    use: [
                        // Require all Android app components
                        platform === "android" && {
                            loader: "nativescript-dev-webpack/android-app-components-loader",
                            options: { modules: appComponents }
                        },

                        {
                            loader: "nativescript-dev-webpack/bundle-config-loader",
                            options: {
                                angular: true,
                                loadCss: !snapshot, // load the application css if in debug mode
                            }
                        },
                    ].filter(loader => !!loader)
                },

                { test: /\.html$|\.xml$/, use: "raw-loader" },

                // tns-core-modules reads the app.css and its imports using css-loader
                {
                    test: /[\/|\\]app\.css$/,
                    use: {
                        loader: "css-loader",
                        options: { minimize: false, url: false },
                    }
                },
                {
                    test: /[\/|\\]app\.scss$/,
                    use: [
                        { loader: "css-loader", options: { minimize: false, url: false } },
                        "sass-loader"
                    ]
                },

                // Angular components reference css files and their imports using raw-loader
                { test: /\.css$/, exclude: /[\/|\\]app\.css$/, use: "raw-loader" },
                { test: /\.scss$/, exclude: /[\/|\\]app\.scss$/, use: ["raw-loader", "resolve-url-loader", "sass-loader"] },

                // Compile TypeScript files with ahead-of-time compiler.
                {
                    test: /.ts$/, use: [
                        "nativescript-dev-webpack/moduleid-compat-loader",
                        "@ngtools/webpack",
                    ]
                },

                // Mark files inside `@angular/core` as using SystemJS style dynamic imports.
                // Removing this will cause deprecation warnings to appear.
                {
                    test: /[\/\\]@angular[\/\\]core[\/\\].+\.js$/,
                    parser: { system: true },
                },
            ],
        },
        plugins: [
            // Define useful constants like TNS_WEBPACK
            new webpack.DefinePlugin({
                "global.TNS_WEBPACK": "true",
                "process": undefined,
            }),
            // Remove all files from the out dir.
            new CleanWebpackPlugin([ `${dist}/**/*` ]),
            // Copy native app resources to out dir.
            new CopyWebpackPlugin([
                {
                    from: `${appResourcesFullPath}/${appResourcesPlatformDir}`,
                    to: `${dist}/App_Resources/${appResourcesPlatformDir}`,
                    context: projectRoot
                },
            ]),
            // Copy assets to out dir. Add your own globs as needed.
            new CopyWebpackPlugin([
                { from: "App_Resources/**" },
                { from: "fonts/**" },
                { from: "**/*.jpg" },
                { from: "**/*.png" },
                { from: "**/*.xml" },
                { from: "**/*.css" },
            ], { ignore: [`${relative(appPath, appResourcesFullPath)}/**`] }),
            // Generate a bundle starter script and activate it in package.json
            new nsWebpack.GenerateBundleStarterPlugin([
                "./vendor",
                "./bundle",
            ]),
            // For instructions on how to set up workers with webpack
            // check out https://github.com/nativescript/worker-loader
            new NativeScriptWorkerPlugin(),

            new AngularCompilerPlugin({
                hostReplacementPaths: nsWebpack.getResolver([platform, "tns"]),
                entryModule: resolve(appPath, "app.module#AppModule"),
                tsConfigPath: join(__dirname, "tsconfig.esm.json"),
                skipCodeGeneration: !aot,
                sourceMap: !!sourceMap,
            }),
            // Does IPC communication with the {N} CLI to notify events when running in watch mode.
            new nsWebpack.WatchStateLoggerPlugin(),
        ],
    };

    if (report) {
        // Generate report files for bundles content
        config.plugins.push(new BundleAnalyzerPlugin({
            analyzerMode: "static",
            openAnalyzer: false,
            generateStatsFile: true,
            reportFilename: resolve(projectRoot, "report", `report.html`),
            statsFilename: resolve(projectRoot, "report", `stats.json`),
        }));
    }

    if (snapshot) {
        config.plugins.push(new nsWebpack.NativeScriptSnapshotPlugin({
            chunk: "vendor",
            angular: true,
            requireModules: [
                "reflect-metadata",
                "@angular/platform-browser",
                "@angular/core",
                "@angular/common",
                "@angular/router",
                "nativescript-angular/platform-static",
                "nativescript-angular/router",
            ],
            projectRoot,
            webpackConfig: config,
        }));
    }

    return config;
};

Describe the bug

I get the following error on executing the following from the CLI

tns prepare ios --release --bundle --env.aot --env.uglify

Copying template files...
Platform ios successfully added. v4.2.0
Executing before-shouldPrepare hook from /Users/Projects/abc/hooks/before-shouldPrepare/nativescript-dev-webpack.js
Executing before-prepare hook from /Users/Projects/abc/hooks/before-prepare/nativescript-dev-typescript.js
Hook skipped because either bundling or livesync is in progress.
Executing before-prepare hook from /Users/Projects/abc/hooks/before-prepare/nativescript-plugin-firebase.js
Preparing project...
Executing before-prepareJSApp hook from /Users/Projects/abc/hooks/before-prepareJSApp/nativescript-dev-webpack.js
Running webpack for ios...
One CLI for webpack must be installed. These are recommended choices, delivered as separate packages:
 - webpack-cli (https://github.com/webpack/webpack-cli)
   The original webpack full-featured CLI.
We will use "npm" to install the CLI via "npm install -D".
Do you want to install 'webpack-cli' (yes/no): y
Installing 'webpack-cli' (running 'npm install -D webpack-cli')...
npm WARN [email protected] requires a peer of webpack@^3.1.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of tns-core-modules@^3.0.0 || ^3.0.0-rc.1 but none is installed. You must install peer dependencies yourself.

+ [email protected]
added 25 packages in 7.426s
{ Error: Cannot find module 'webpack-bundle-analyzer'
    at Function.Module._resolveFilename (module.js:547:15)
    at Function.Module._load (module.js:474:25)
    at Module.require (module.js:596:17)
    at require (/Users/Projects/abc/node_modules/v8-compile-cache/v8-compile-cache.js:159:20)
    at Object.<anonymous> (/Users/Projects/abc/webpack.config.js:8:34)
    at Module._compile (/Users/Projects/abc/node_modules/v8-compile-cache/v8-compile-cache.js:178:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (/Users/Projects/abc/node_modules/v8-compile-cache/v8-compile-cache.js:159:20)
    at WEBPACK_OPTIONS (/Users/Projects/abc/node_modules/webpack-cli/bin/convert-argv.js:133:13)
    at requireConfig (/Users/Projects/abc/node_modules/webpack-cli/bin/convert-argv.js:135:6)
    at /Users/Projects/abc/node_modules/webpack-cli/bin/convert-argv.js:142:17
    at Array.forEach (<anonymous>)
    at module.exports (/Users/Projects/node_modules/webpack-cli/bin/convert-argv.js:140:15)
    at yargs.parse (/Users/Projects/abc/node_modules/webpack-cli/bin/cli.js:241:39)
    at Object.parse (/Users/Projects/abc/node_modules/yargs/yargs.js:563:18)
    at /Users/Projects/abc/node_modules/webpack-cli/bin/cli.js:219:8
    at Object.<anonymous> (/Users/Projects/abc/node_modules/webpack-cli/bin/cli.js:538:3)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at runCommand.then (/Users/Projects/abc/node_modules/webpack/bin/webpack.js:142:5)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7) code: 'MODULE_NOT_FOUND' }
Executing webpack failed with exit code 1.
# tns prepare

Error started happening after I upgraded to nativescirpt-dev-webpack version 0.16.2 to prevent this error.

@anuragd7 anuragd7 changed the title Cannot find Cannot find module 'webpack-bundle-analyzer' Oct 15, 2018
@NickIliev
Copy link
Contributor

@anuragd7 remove all unused dev dependencies and then run the upgrade script from nativescript-dev-webpack

npm i nativescript-dev-webpack@latest --save-dev
./node_modules/.bin/update-ns-webpack --deps --configs

Or if you need to use the webpack analyzer install it as a devDependency

npm install webpack-bundle-analyzer --save-dev

@anuragd7
Copy link
Author

anuragd7 commented Oct 23, 2018

@NickIliev Thanks for the suggestion. I have currently downgraded to Xcode 9 and the project is building as expected there without needing to make any changes. Will probably need some time before I can try out the suggestion on Xcode 10. Will post my findings on the thread then. Thanks again.

@anuragd7
Copy link
Author

@NickIliev Thanks. Have just upgraded to NS 5.0 - Can confirm that the project builds with webpack using Xcode 10 now. However, the styles in the phone.ios.css is not applied. I am closing this issue and opening a new one for the same.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

2 participants