Ng2-translate与webpack不兼容

时间:2018-10-18 11:08:05

标签: javascript angular webpack nativescript

早上好。 我在我的应用程序中使用ng2-translate插件,运行tns run ios效果很好。 但是当使用命令tns运行ios --bundle --env.uglify --env.aot时,webpack会进行复制而不会给出任何错误,但是打开时会出现错误应用程序:

CONSOLE LOG file:///app/vendor.js:1:1200993:
CONSOLE ERROR file:///app/vendor.js:1:28276: ERROR TypeError: this.http.get(this.prefix+"/"+e+this.suffix).map is not a function. (In 'this.http.get(this.prefix+"/"+e+this.suffix).map(function(e){return e.json()})', 'this.http.get(this.prefix+"/"+e+this.suffix).map' is undefined)
CONSOLE ERROR file:///app/vendor.js:1:1125775: bootstrap: ERROR BOOTSTRAPPING ANGULAR
CONSOLE ERROR file:///app/vendor.js:1:1125775: bootstrap: this.http.get(this.prefix+"/"+e+this.suffix).map is not a function. (In 'this.http.get(this.prefix+"/"+e+this.suffix).map(function(e){return e.json()})', 'this.http.get(this.prefix+"/"+e+this.suffix).map' is undefined)
getTranslation@file:///app/vendor.js:1:886381
getTranslation@file:///app/vendor.js:1:887491
retrieveTranslations@file:///app/vendor.js:1:887380
setDefaultLang@file:///app/vendor.js:1:886824
n@file:///app/bundle.js:1:88782
ka@file:///app/vendor.js:1:110925

以前有人遇到过这个问题吗?

我已经使用本地脚本https://www.npmjs.com/package/@ngx-translate/core测试了此插件,但未成功。

2 个答案:

答案 0 :(得分:0)

如果您使用JSON文件存储字符串,请确保Webpack的复制插件配置中包含了这些字符串。

答案 1 :(得分:0)

是的,它已添加到webpack中,这是我当前的配置:

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/<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 = `${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: 'styles/css/**' },
            { from: "assets/i18n/*.json"},
            { from: "**/*.jpg" },
            { from: "**/*.png" },
        ], { 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;

};