Sunday 21 May 2017

How to webpack .cshtml views as templateUrl in Angular 2

I have setup my Angular 2 project in .NET Core solution and I have a situation where I need to use .cshtml view files to be rendered from server and use them as templates in Angular components. I am using webpack to AOT bundle them.

How can I exclude templateUrl or template to be excluded (not to be compiled into output .js file) but rather resolved on the fly?

My lazy load component (notfound.component.ts):

import { Component } from "@angular/core";

@Component({
    templateUrl: "/Home/PageNotFound" // This is my Controller/Action
})
export class NotFoundComponent
{
}

webpack.config.js:

var webpack = require("webpack");
var clean = require("clean-webpack-plugin");
var compression = require("compression-webpack-plugin");
var path = require("path");
var analyzer = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;

var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: {
        "app": "./Client/main-aot.ts" // AoT compilation
    },

    devtool: "source-map",

    output: {
        path: __dirname + "/wwwroot/dist/bundle",
        //filename: "[name]-[hash:8].bundle.js",
        filename: "[name].js",
        chunkFilename: "[id]-[hash:8].chunk.js",
        publicPath: "/dist/bundle/",
    },

    resolve: {
        extensions: [".ts", ".js"]
    },

    module: {
        rules: [
            {
                test: /\.ts$/,
                use: [
                    "awesome-typescript-loader",
                    "angular-router-loader?aot=true&genDir=aot/"
                ]
            }
        ],
        exprContextCritical: false
    },
    plugins: [
        new clean(
            [
                __dirname + "/wwwroot/dist/bundle"
            ]
        ),
        new analyzer(),
        new webpack.LoaderOptionsPlugin({
        minimize: true,
        debug: false
        }),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            },
            output: {
                comments: false
            },
            sourceMap: true
        }),
        new compression({
            asset: "[path].gz[query]",
            algorithm: "gzip",
            test: /\.js$|\.html$/,
            threshold: 10240,
            minRatio: 0.8
        })
    ]
};

When I run following NPM command, its giving me error:

"node_modules/.bin/ngc -p tsconfig-aot.json" && webpack --configebpack.config.js

Error: Compilation failed. Resource file not found: C:/Users/Saad/Documents/Visual Studio 2017/Projects/HelloAngular/HelloAngular/Client/notfound/dist/template/notfound/notfound.html



via Saad Ahmed Khan

No comments:

Post a Comment