NativeScript / nativescript-dev-webpack

A package to help with webpacking NativeScript apps.
Apache License 2.0
97 stars 49 forks source link

Two files in nativescript-dev-webpack prevent uglify from running #713

Open gsmedley opened 5 years ago

gsmedley commented 5 years ago

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):

{
  "description": "Kanayo",
  "license": "SEE LICENSE IN ",
  "readme": "NativeScript Application",
  "repository": "",
  "nativescript": {
    "id": "com.kanayo.mymobilenative",
    "tns-ios": {
      "version": "4.2.0"
    },
    "tns-android": {
      "version": "4.2.0"
    }
  },
  "dependencies": {
    "@angular/common": "6.1.8",
    "@angular/compiler": "6.1.8",
    "@angular/core": "6.1.8",
    "@angular/forms": "6.1.8",
    "@angular/http": "6.1.8",
    "@angular/platform-browser": "6.1.8",
    "@angular/platform-browser-dynamic": "6.1.8",
    "@angular/router": "6.1.8",
    "@types/i18next": "11.9.0",
    "aes-js": "3.1.1",
    "angular": "1.7.4",
    "bigdecimal": "0.6.1",
    "i18next": "11.9.0",
    "jsrsasign": "8.0.12",
    "moment": "2.22.2",
    "nativescript-angular": "6.1.0",
    "nativescript-anyline": "file:plugins/nativescript-anyline/publish/package/nativescript-anyline-2.3.1.tgz",
    "nativescript-bcryptjs": "1.0.1",
    "nativescript-bluetooth": "file:plugins/nativescript-bluetooth-2.0.3.tgz",
    "nativescript-cardview": "file:plugins/nativescript-cardview-3.1.1.tgz",
    "nativescript-checkbox": "file:plugins/nativescript-checkbox.tgz",
    "nativescript-dialogs": "file:plugins/nativescript-dialogs/publish/package/nativescript-dialogs-0.0.1.tgz",
    "nativescript-floatingactionbutton": "4.1.4",
    "nativescript-idscanner": "file:plugins/nativescript-idscanner/publish/package/nativescript-idscanner-0.0.1.tgz",
    "nativescript-ios-uuid": "file:plugins/nativescript-ios-uuid-1.0.0.tgz",
    "nativescript-iqkeyboardmanager": "1.3.0",
    "nativescript-local-notifications": "git+https://github.com/chuckmitchell/nativescript-local-notifications.git",
    "nativescript-medicalsensors": "file:plugins/nativescript-medicalsensors",
    "nativescript-ng2-fonticon": "1.3.4",
    "nativescript-orientation": "2.2.1",
    "nativescript-pdf-view": "2.0.1",
    "nativescript-permissions": "1.2.3",
    "nativescript-secure-storage": "2.3.0",
    "nativescript-swift-3.0": "1.0.0",
    "nativescript-textinputlayout": "2.0.6",
    "nativescript-texttospeech": "file:plugins/nativescript-texttospeech",
    "nativescript-theme-core": "1.0.4",
    "nativescript-toast": "1.4.6",
    "nativescript-ui-chart": "3.9.0",
    "nativescript-ui-sidedrawer": "4.3.0",
    "nativescript-unit-test-runner": "0.3.4",
    "nativescript-urlhandler": "1.2.2",
    "nativescript-videoplayer": "4.2.0",
    "reflect-metadata": "0.1.12",
    "rxjs": "6.3.2",
    "rxjs-compat": "6.3.2",
    "semver": "5.5.1",
    "tns-core-modules": "^4.2.1",
    "tns-platform-declarations": "4.2.1",
    "zone.js": "0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/core": "0.8.3",
    "@angular/compiler-cli": "6.1.8",
    "@ngtools/webpack": "6.2.3",
    "@types/jasmine": "2.8.8",
    "babel-traverse": "6.26.0",
    "babel-types": "6.26.0",
    "babylon": "6.18.0",
    "clean-webpack-plugin": "0.1.19",
    "copy-webpack-plugin": "4.5.2",
    "css-loader": "1.0.0",
    "extract-text-webpack-plugin": "3.0.2",
    "jasmine-core": "3.2.1",
    "karma": "3.0.0",
    "karma-jasmine": "1.1.2",
    "karma-nativescript-launcher": "0.4.0",
    "lazy": "1.0.11",
    "nativescript-custom-entitlements": "0.2.0",
    "nativescript-dev-sass": "1.6.0",
    "nativescript-dev-typescript": "0.7.4",
    "nativescript-dev-webpack": "0.16.1",
    "nativescript-worker-loader": "0.9.1",
    "raw-loader": "0.5.1",
    "resolve-url-loader": "3.0.0",
    "rimraf": "2.6.2",
    "sass-loader": "7.1.0",
    "typescript": "2.7.2",
    "uglifyjs-webpack-plugin": "2.0.1",
    "webpack": "4.19.1",
    "webpack-bundle-analyzer": "3.0.2",
    "webpack-cli": "3.1.1",
    "webpack-sources": "1.3.0"
  },
  "scripts": {
    "build.clean": "rimraf ./node_modules && rimraf ./package-lock.json && tns platform remove android  || tns platform remove ios",
    "build.plugins": "npm run build.plugins.anylne && npm run build.plugins.idscanner && npm run build.plugins.dialogs ",
    "build.plugins.anylne": "cd plugins/nativescript-anyline/publish && npm run build",
    "build.plugins.idscanner": "cd plugins/nativescript-idscanner/publish && npm run build",
    "build.plugins.dialogs": "cd plugins/nativescript-dialogs/publish && npm run build"
  }
}
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 { nsReplaceBootstrap } = require("nativescript-dev-webpack/transformers/ns-replace-bootstrap");
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//...
    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 = `${nsWebpack.getEntryModule(appFullPath)}.ts`;
    const entryPath = `.${sep}${entryModule}`;

    const ngCompilerPlugin = new AngularCompilerPlugin({
        hostReplacementPaths: nsWebpack.getResolver([platform, "tns"]),
        platformTransformers: aot ? [nsReplaceBootstrap(() => ngCompilerPlugin)] : null,
        mainPath: resolve(appPath, entryModule),
        tsConfigPath: join(__dirname, "tsconfig.tns.json"),
        skipCodeGeneration: !aot,
        sourceMap: !!sourceMap,
    });

    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"] },

                {
                    test: /(?:\.ngfactory\.js|\.ngstyle\.js|\.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: "fonts/**" },
                { from: "**/*.jpg" },
                { from: "**/*.png" },
                { from: "**/*.gif" },
                { from: "**/*.xml" },
                { from: "**/*.json" },
                { from: "**/*.css" },
                { from: "**/*.txt" }
            ], { 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(),
            ngCompilerPlugin,
            // 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 Building with --env.uglify fails due to some ES6 code in nativescript-dev-webpack itself. None of my plugins have any and I was able to verify that changing two nativescript-dev-webpack files allowed uglify to run.

load-application-css-angular.js load-application-css.js

Rewritten as:

var loadCss = require("./load-application-css");

module.exports = function() {
    loadCss(function() {
        global.registerModule("./app.css", function(){ return require("~/app")});
    });
}

module.exports = function (loadModuleFn) {
    var application = require("tns-core-modules/application");
    require("tns-core-modules/ui/styling/style-scope");

    loadModuleFn();

    application.loadAppCss();
}
NickIliev commented 5 years ago

@gsmedley the latest version of nativescript-dev-webpack seems to have the rewritten files in its code (e.g. here) - or do you mean that they should be re-written?

gsmedley commented 5 years ago

For me, Uglify is choking on the "const" in that file, above is how I rewrote them to work with Uglify. If you decide this is a good idea, should probably do load-application-css-regular.js as well.