Material 2 attributes in Angular 4 aren't working with webpack, ASP.NET - asp.net

I'm trying to get Material 2 to work with Angular 4.4.6 using webpack in an ASP.NET Core 2 web application. I get no errors but I currently get no styling and the mat-button attribute has no effect on the output DOM.
I have done the following:
Environment is as follows:
Visual Studio (Professional) 2017 version 15.4.0
ASP.NET Core 2 web application with Angular, from VS template
Update #angular packages to ^4.4.6 in NPM and restore packages
"#angular/animations": "^4.4.6",
"#angular/common": "^4.4.6",
"#angular/compiler": "^4.4.6",
"#angular/compiler-cli": "^4.4.6",
"#angular/core": "^4.4.6",
"#angular/forms": "^4.4.6",
"#angular/http": "^4.4.6",
"#angular/platform-browser": "^4.4.6",
"#angular/platform-browser-dynamic": "^4.4.6",
"#angular/platform-server": "^4.4.6",
"#angular/router": "^4.4.6",
Per the Material guide, run the following command in the project directory:
npm install --save #angular/material #angular/cdk
Update webpack.config.vendor.js to add the following lines to the treeShakableModules array, just after '#angular/router':
'#angular/material',
'#angular/material/prebuilt-themes/deeppurple-amber.css',
In app.module.browser.ts, import the module:
import { MatButtonModule } from '#angular/material';
#NgModule({
bootstrap: [ AppComponent ],
imports: [
BrowserModule,
MatButtonModule,
AppModuleShared
],
providers: [
{ provide: 'BASE_URL', useFactory: getBaseUrl }
]
})
In home.component.html, add the following line at the end of the file:
<button mat-raised-button>This is a button</button>
From the project directory, run webpack to update the vendor files:
webpack --config webpack.config.vendor.js
Build and run the application
Observe the home page button is not styled. There are no errors in the console suggesting missing styles or invalid attributes.
I have the following configuration:
Angular 4.4.6
Material 2.0.0-beta.12
Windows 10 Professional
TypeScript 2.4.1 (NPM)
Chrome Version 61.0.3163.100 (Official Build) (64-bit)
Verified the styles do exist, as specifying class="mat-raised-button" on the button has an effect (though it does not look like the raised button) it does change the interior styling of the button.
I note that the attribute does not appear to have any effect on the styling or content of the output HTML (versus what I see when inspecting the elements on the guide website), suggesting that something has gone wrong with the setup of the module, but I can't for the life of me figure out what that might be.
EDIT: By request, here is the webpack.config.vendor.js up to the boilerplate:
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const merge = require('webpack-merge');
const treeShakableModules = [
'#angular/animations',
'#angular/common',
'#angular/compiler',
'#angular/core',
'#angular/forms',
'#angular/http',
'#angular/platform-browser',
'#angular/platform-browser-dynamic',
'#angular/router',
'zone.js',
];
const nonTreeShakableModules = [
'#angular/cdk',
'#angular/material',
'#angular/material/button',
'#angular/material/prebuilt-themes/deeppurple-amber.css',
'bootstrap',
'bootstrap/dist/css/bootstrap.css',
'es6-promise',
'es6-shim',
'event-source-polyfill',
'jquery',
];
const allModules = treeShakableModules.concat(nonTreeShakableModules);
module.exports = (env) => {
const extractCSS = new ExtractTextPlugin('vendor.css');
const isDevBuild = !(env && env.prod);
const sharedConfig = {
stats: { modules: false },
resolve: { extensions: [ '.js' ] },
module: {
rules: [
{ test: /\.(png|woff|woff2|eot|ttf|svg)(\?|$)/, use: 'url-loader?limit=100000' }
]
},
output: {
publicPath: 'dist/',
filename: '[name].js',
library: '[name]_[hash]'
},
plugins: [
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }), // Maps these identifiers to the jQuery package (because Bootstrap expects it to be a global variable)
new webpack.ContextReplacementPlugin(/\#angular\b.*\b(bundles|linker)/, path.join(__dirname, './ClientApp')), // Workaround for https://github.com/angular/angular/issues/11580
new webpack.ContextReplacementPlugin(/angular(\\|\/)core(\\|\/)#angular/, path.join(__dirname, './ClientApp')), // Workaround for https://github.com/angular/angular/issues/14898
new webpack.IgnorePlugin(/^vertx$/) // Workaround for https://github.com/stefanpenner/es6-promise/issues/100
]
};
... boilerplate follows this ...

So somewhat counterintuitively, the solution requires that the module importing be done in app.module.shared.ts, not app.module.browser.ts. If you are using the default Angular template, use the same steps as above, except for step 5, do the following:
Edit app.module.shared.ts to add the MatButtonModule module as an import, as follows:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { RouterModule } from '#angular/router';
import { MatButtonModule } from '#angular/material/button';
import { AppComponent } from './components/app/app.component';
import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { HomeComponent } from './components/home/home.component';
import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
import { CounterComponent } from './components/counter/counter.component';
#NgModule({
declarations: [
AppComponent,
NavMenuComponent,
CounterComponent,
FetchDataComponent,
HomeComponent
],
imports: [
CommonModule,
HttpModule,
FormsModule,
MatButtonModule,
RouterModule.forRoot([
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'counter', component: CounterComponent },
{ path: 'fetch-data', component: FetchDataComponent },
{ path: '**', redirectTo: 'home' }
])
]
})
export class AppModuleShared {
}
Note also it is not necessary to add #angular/cdk or #angular/material/button to the modules list in webpack.config.vendor.js. It is sufficient to add the ones described in the guide.
See: https://github.com/angular/material2/issues/7997

According to official docs Here
You've to Import theming to your Global style file this is as simple as including one line in your styles.css file:
#import '~#angular/material/prebuilt-themes/deeppurple-amber.css';
or Alternatively, you can just reference the file directly.
Available pre-built themes:
deeppurple-amber.css
indigo-pink.css
pink-bluegrey.css
purple-green.css

Related

Vite import generetad chunks in index.js with url

in my Vue3 project I import the components in the router index.js like that:
{
path: settingsStore.startUri,
name: "home",
component: () => import("../views/Home/Home.vue"),
},
My vite.config looks like that:
import { defineConfig } from "vite";
import vue from "#vitejs/plugin-vue";
import vuetify from "vite-plugin-vuetify";
const path = require("path");
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
// https://github.com/vuetifyjs/vuetify-loader/tree/next/packages/vite-plugin
vuetify({
autoImport: true,
}),
],
define: {
"process.env": {},
__VUE_I18N_FULL_INSTALL__: true,
__VUE_I18N_LEGACY_API__: false,
__INTLIFY_PROD_DEVTOOLS__: false,
},
resolve: {
alias: {
"#": path.resolve(__dirname, "src"),
},
},
build: {
rollupOptions: {
output: {
entryFileNames: "news-[name].js",
assetFileNames: "news-[name].[ext]",
manualChunks: undefined,
chunkFileNames: "chunks/[name].js",
},
},
},
optimizeDeps: {
include: ["vue", "axios"],
},
});
When I run npm run build it creates a chunk directory with some smaller .js files beeing imported in the index.js but as relativ paths like that:
import("./chunks/Home.js")
But I need to import the files from an url like that:
import("https://example.com/chunks/Home.js")
Does anyone know if thats possible and how can I do that?
I tried a lot, read a lot of documentations but didnt find an answer

TailwindCSS 3.0 Upgrade overriding button styles

Problem:
Button class being overridden by default tailwind base classes. Not sure why my classes on the element aren't being applied.
Question:
How can I get my styles to apply properly?
Screenshot:
As you can see background color on .documentCategory__row is being overridden by button, [type=button] on index.scss which is being defined within #tailwind/base.
/* index.scss */
:root {
--color-primary: #00a3e0;
--color-secondary: #470a68;
--color-success: #87d500;
--color-accent: #e87722;
/* Dark themes below */
--color-dark-primary: rgba(31, 41, 55, 1);
--dark-text: rgba(187, 193, 198, 1);
}
#import "tailwindcss/base";
#import "tailwindcss/components";
#import "tailwindcss/utilities";
I'm not sure if this has to do with me switching to dart-scss so here is my webpack configuration in case I am missing something
import path from 'path'
import { Configuration as WebpackConfiguration, HotModuleReplacementPlugin } from 'webpack'
import { Configuration as WebpackDevServerConfiguration } from 'webpack-dev-server';
import HtmlWebpackPlugin from 'html-webpack-plugin'
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin'
import ESLintPlugin from 'eslint-webpack-plugin'
import tailwindcss from 'tailwindcss'
import autoprefixer from 'autoprefixer'
const CopyPlugin = require('copy-webpack-plugin');
interface Configuration extends WebpackConfiguration {
devServer?: WebpackDevServerConfiguration;
}
const config: Configuration = {
mode: 'development',
devServer: {
static: path.join(__dirname, 'build'),
historyApiFallback: true,
port: 4000,
open: true,
hot: true,
},
output: {
publicPath: '/',
},
entry: './src/index.tsx',
module: {
rules: [
{
test: /\.(ts|js)x?$/i,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-env',
'#babel/preset-react',
'#babel/preset-typescript',
],
},
},
},
{
test: /\.(sa|sc|c)ss$/i,
use: [
'style-loader',
'css-loader',
'sass-loader',
{
loader: 'postcss-loader', // postcss loader needed for tailwindcss
options: {
postcssOptions: {
ident: 'postcss',
plugins: [tailwindcss, autoprefixer],
},
},
},
],
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
loader: 'file-loader',
options: {
outputPath: '../fonts',
},
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
plugins: [
new HtmlWebpackPlugin({
template: 'public/index.html',
}),
new HotModuleReplacementPlugin(),
new CopyPlugin({
patterns: [
// relative path is from src
{ from: 'public/images', to: 'images' },
],
}),
// Add type checking on dev run
new ForkTsCheckerWebpackPlugin({
async: false,
}),
// Add lint checking on dev run
new ESLintPlugin({
extensions: ['js', 'jsx', 'ts', 'tsx'],
}),
],
devtool: 'inline-source-map',
};
export default config
If there are other files I am missing that are needed let me know!
without seeing what your index.tsx looks like I can only make a guess, but here's what caused this issue in our app:
in our index.tsx we were importing index.css after importing our component tree with import App from 'src/App. thus the css was loaded into the site in the wrong order. imports from components first (css modules, normal css imports), tailwind last.
go to your entry file (probably index.tsx) and try moving your import 'index.scss' line above importing the root component.
like this for example
/* index.tsx */
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css'; // this file holds all tailwind styles
import { App } from 'src/App';
// ...
read more here:
https://github.com/tailwindlabs/tailwindcss/discussions/7304#discussioncomment-2256226
Even i faced the same issue but I am using Vue3 + element-ui-plus, after spending more than 6 hours my solution is to set :native-type='null':
<el-button type='primary' round #click='handleClick' :native-type='null'>Click Me</el-button>
but this is kinda "hack", this either need to be fixed by Tailwind or by element-ui team. Anyhow, for now enjoy ;)
And the discussion is on here
I got the same issue using tailwindcss v3 and NextUI, and button's background were "transparent". By adding type = {null}, to button's I solve the issue

Vuetify CSS missing when i build for production

We purchased a web app written in Vue from someone and we developing to change/improve it. One thing we added was Vuetify so we can use the Vuetify elements and everything has been working great while in development mode, but when we build for production the CSS for Vuetify elements is missing.
I have searched for this online already and have already tried what everybody is suggesting without any luck.
Anybody has an idea of what could be wrong and why npm run build would be missing some of the CSS?
What's weird is that all the UI functionality for Vue elements is working perfectly, just the CSS is missing.
Please see code samples below.
main.js:
import '#fortawesome/fontawesome-free/css/all.css'
import Vue from "vue";
import App from "./App.vue";
import VueMoment from "vue-moment";
import VueAnalytics from "vue-analytics";
import VueMeta from "vue-meta";
import { library } from "#fortawesome/fontawesome-svg-core";
import {
faCoffee,
faPlusCircle,
faChartLine,
faChevronDown,
faMobile,
faEnvelope,
faClock,
faUsers,
faPaperPlane,
faCheckCircle,
faCheck,
faLeaf,
} from "#fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "#fortawesome/vue-fontawesome";
import axios from "axios";
import router from "./router";
import store from "./store";
import vuetify from './plugins/vuetify';
import Vuetify from 'vuetify/lib'
library.add([
faCoffee,
faPlusCircle,
faChartLine,
faChevronDown,
faMobile,
faEnvelope,
faClock,
faUsers,
faPaperPlane,
faCheckCircle,
faCheck,
faLeaf,
]);
Vue.use(VueAnalytics, {
id: "xxx",
router,
});
Vue.use(VueMoment);
Vue.use(VueMeta);
Vue.component("font-awesome-icon", FontAwesomeIcon);
Vue.use(Vuetify)
axios.interceptors.response.use(undefined, async function (error) {
if (error.response.status === 401) {
await store.dispatch("auth/logout");
router.push("/login");
}
return Promise.reject(error);
});
// Plugins
// ...
// Sass file
require("./assets/styles/main.css");
Vue.config.productionTip = false;
new Vue({
router,
store,
vuetify,
render: (h) => h(App)
}).$mount("#app");
App.vue:
<template>
<v-app>
<v-main>
<router-view/>
</v-main>
</v-app>
</template>
<style>
.text-white {
color: #fff !important;
}
.text-gray-600 {
color: #757575 !important;
}
.font-semibold, .text-gray-700 {
color: #616161 !important;
}
</style>
package.json:
{
"name": "reviewgrower-spa",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"deploy": "git push dokku master"
},
"dependencies": {
"#fortawesome/fontawesome-svg-core": "^1.2.25",
"#fortawesome/free-solid-svg-icons": "^5.11.2",
"#fortawesome/vue-fontawesome": "^0.1.8",
"#fullhuman/postcss-purgecss": "^1.3.0",
"axios": "^0.19.0",
"chart.js": "^2.9.4",
"core-js": "^2.6.10",
"i": "^0.3.6",
"jquery": "^3.5.1",
"npm": "^6.13.0",
"tailwindcss-spinner": "^0.2.0",
"tailwindcss-toggle": "github:TowelSoftware/tailwindcss-toggle",
"url-parse": "^1.4.7",
"vue": "^2.6.10",
"vue-analytics": "^5.17.2",
"vue-chartjs": "^3.5.1",
"vue-click-outside": "^1.0.7",
"vue-clickaway": "^2.2.2",
"vue-feather-icons": "^4.22.0",
"vue-js-toggle-button": "^1.3.3",
"vue-meta": "^1.6.0",
"vue-moment": "^4.0.0",
"vue-router": "^3.1.3",
"vue-stripe-elements-plus": "^0.2.10",
"vuetify": "^2.4.0",
"vuex": "^3.0.1",
"vuex-persist": "^2.1.1"
},
"devDependencies": {
"#fortawesome/fontawesome-free": "^5.15.2",
"#vue/cli-plugin-babel": "^3.12.1",
"#vue/cli-plugin-eslint": "^3.12.1",
"#vue/cli-service": "^3.12.1",
"babel-eslint": "^10.0.3",
"eslint": "^5.16.0",
"eslint-plugin-vue": "^5.2.3",
"sass": "^1.32.0",
"sass-loader": "^7.1.0",
"tailwindcss": "^1.1.3",
"vue-cli-plugin-vuetify": "~2.1.0",
"vue-template-compiler": "^2.5.21",
"vuetify-loader": "^1.7.0"
}
}
It's a little tough to understand what is missing where. If you think that is just missing then please try adding css onto the HTML file from the cdn and check the working.
<link href="https://cdn.jsdelivr.net/npm/vuetify#2.x/dist/vuetify.min.css" rel="stylesheet">
I see that you are using webpack to compile the code. So, this could be also something related to webpack configuration. In your webpack rules do you have rules for css and scss. Because vuetify files are in scss.
My webpack configuration is as below when I do these type of circus.
--webpack.config.js--
const path = require("path");
const VuetifyLoaderPlugin = require("vuetify-loader/lib/plugin");
const { VueLoaderPlugin } = require("vue-loader");
module.exports = {
watch: true,
entry: {
main: 'main.js'
},
module: {
rules: [
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
{
test: /\.vue$/,
use: "vue-loader",
},
{
test: /\.s(c|a)ss$/,
use: [
"vue-style-loader",
"css-loader",
{
loader: "sass-loader",
// Requires sass-loader#^8.0.0
// options: {
// implementation: require('sass'),
// sassOptions: {
// fiber: require('fibers'),
// indentedSyntax: true // optional
// },
// },
},
],
},
],
},
plugins: [
new VueLoaderPlugin(),
new VuetifyLoaderPlugin({
/**
* This function will be called for every tag used in each vue component
* It should return an array, the first element will be inserted into the
* components array, the second should be a corresponding import
*
* originalTag - the tag as it was originally used in the template
* kebabTag - the tag normalised to kebab-case
* camelTag - the tag normalised to PascalCase
* path - a relative path to the current .vue file
* component - a parsed representation of the current component
*/
match(originalTag, { kebabTag, camelTag, path, component }) {
if (kebabTag.startsWith("core-")) {
return [
camelTag,
`import ${camelTag} from '#/components/core/${camelTag.substring(
4
)}.vue'`,
];
}
},
}),
],
}
Check your postcss.config.js, see if it has something to do with the purgecss.
You have to config the whitelist to ignore the vuetify styles.
Here is a sample for your reference:
const autoprefixer = require("autoprefixer");
const postcssImport = require("postcss-import");
const purgecss = require("#fullhuman/postcss-purgecss");
const IS_PROD = ["production", "prod"].includes(process.env.NODE_ENV);
let plugins = [];
if (IS_PROD) {
plugins.push(postcssImport);
plugins.push(
purgecss({
content: [
"./src/**/*.vue",
"./public/**/*.html",
`./node_modules/vuetify/src/**/*.ts`,
`./node_modules/vuetify/dist/vuetify.css`
],
defaultExtractor (content) {
const contentWithoutStyleBlocks = content.replace(/<style[^]+?<\/style>/gi, '')
return contentWithoutStyleBlocks.match(/[A-Za-z0-9-_/:]*[A-Za-z0-9-_/]+/g) || []
},
safelist: [ /-(leave|enter|appear)(|-(to|from|active))$/, /^(?!(|.*?:)cursor-move).+-move$/, /^router-link(|-exact)-active$/, /data-v-.*/ ],
whitelist: [
'container',
'row',
'spacer',
'aos-animate',
'col',
'[type=button]',
'v-application p',
],
whitelistPatterns: [
/^v-.*/,
/^col-.*/,
/^theme-.*/,
/^rounded-.*/,
/^data-aos-.*/,
/^(red|grey)--text$/,
/^text--darken-[1-4]$/,
/^text--lighten-[1-4]$/
],
whitelistPatternsChildren: [
/^post-content/,
/^v-input/,
/^swiper-.*/,
/^pswp.*/,
/^v-text-field.*/,
/^v-progress-linear/
]
})
);
}
module.exports = {
plugins:[
require('cssnano')({
preset: 'default'
}),
require('postcss-pxtorem')({
remUnit:15, //每个rem对应的px值
threeVersion:true
}),
...plugins,autoprefixer
]
}``
You are simply missing an include in your main.js (see vuetify docs):
import 'vuetify/dist/vuetify.min.css'
This will ensure that webpack includes the vuetify styles in the bundled CSS for production. This fixed the same issue for me (i.e. it worked locally but not in production).

.Net Core 2 Spa Template with Angular Material

Struggling trying to get Angular Material , or any 3rd party control set really, to work with this new template. In this new template, the webpack is broken into TreeShakable and NonTreeShakable. In addition the app.module is now app.module.shared, app.module.browser, app.module.server.
As I have attempted to get this to work, the app will only run with modules configured in app.module.browser, but the material tags are not getting processed. Trying something simple and trying the button. I don't get any errors but not does it work. I went to their example in Plunker, copied what it generated, and it displays right telling me I got the css in right, at least.
Including the webpack vendor configuration as a starting point, as this seems to be key because how it bundles the css and js.
TIA
Webpack.vendor
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const merge = require('webpack-merge');
const treeShakableModules = [
'#angular/animations',
'#angular/common',
'#angular/compiler',
'#angular/core',
'#angular/forms',
'#angular/http',
'#angular/platform-browser',
'#angular/platform-browser-dynamic',
'#angular/router',
'#angular/material',
'#angular/cdk',
'zone.js'
];
const nonTreeShakableModules = [
'bootstrap',
'jqwidgets-framework',
"#angular/material/prebuilt-themes/indigo-pink.css",
'bootstrap/dist/css/bootstrap.css',
'font-awesome/css/font-awesome.css',
'es6-promise',
'es6-shim',
'event-source-polyfill',
'jquery',
];
const allModules = treeShakableModules.concat(nonTreeShakableModules);
module.exports = (env) => {
const extractCSS = new ExtractTextPlugin('vendor.css');
const isDevBuild = !(env && env.prod);
const sharedConfig = {
stats: { modules: false },
resolve: { extensions: [ '.js' ] },
module: {
rules: [
{ test: /\.(png|woff|woff2|eot|ttf|svg)(\?|$)/, use: 'url-loader?limit=100000' }
]
},
output: {
publicPath: 'dist/',
filename: '[name].js',
library: '[name]_[hash]'
},
plugins: [
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }), // Maps these identifiers to the jQuery package (because Bootstrap expects it to be a global variable)
new webpack.ContextReplacementPlugin(/\#angular\b.*\b(bundles|linker)/, path.join(__dirname, './ClientApp')), // Workaround for https://github.com/angular/angular/issues/11580
new webpack.ContextReplacementPlugin(/angular(\\|\/)core(\\|\/)#angular/, path.join(__dirname, './ClientApp')), // Workaround for https://github.com/angular/angular/issues/14898
new webpack.IgnorePlugin(/^vertx$/) // Workaround for https://github.com/stefanpenner/es6-promise/issues/100
]
};
const clientBundleConfig = merge(sharedConfig, {
entry: {
// To keep development builds fast, include all vendor dependencies in the vendor bundle.
// But for production builds, leave the tree-shakable ones out so the AOT compiler can produce a smaller bundle.
vendor: isDevBuild ? allModules : nonTreeShakableModules
},
output: { path: path.join(__dirname, 'wwwroot', 'dist') },
module: {
rules: [
{ test: /\.css(\?|$)/, use: extractCSS.extract({ use: isDevBuild ? 'css-loader' : 'css-loader?minimize' }) }
]
},
plugins: [
extractCSS,
new webpack.DllPlugin({
path: path.join(__dirname, 'wwwroot', 'dist', '[name]-manifest.json'),
name: '[name]_[hash]'
})
].concat(isDevBuild ? [] : [
new webpack.optimize.UglifyJsPlugin()
])
});
const serverBundleConfig = merge(sharedConfig, {
target: 'node',
resolve: { mainFields: ['main'] },
entry: { vendor: allModules.concat(['aspnet-prerendering']) },
output: {
path: path.join(__dirname, 'ClientApp', 'dist'),
libraryTarget: 'commonjs2',
},
module: {
rules: [ { test: /\.css(\?|$)/, use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize' ] } ]
},
plugins: [
new webpack.DllPlugin({
path: path.join(__dirname, 'ClientApp', 'dist', '[name]-manifest.json'),
name: '[name]_[hash]'
})
]
});
return [clientBundleConfig, serverBundleConfig];
}
You need to include angular material and cdk in nonTreeShakableModules like:
const treeShakableModules = [
'#angular/animations',
'#angular/common',
'#angular/compiler',
'#angular/core',
'#angular/forms',
'#angular/http',
'#angular/platform-browser',
'#angular/platform-browser-dynamic',
'#angular/router',
'zone.js',
];
const nonTreeShakableModules = [
'bootstrap',
'bootstrap/dist/css/bootstrap.css',
'#angular/material',
'#angular/material/prebuilt-themes/indigo-pink.css',
'#angular/cdk',
'es6-promise',
'es6-shim',
'event-source-polyfill',
'jquery',
];
Make sure you have installed both angular material and cdk modules from npm with the following 2 commands (animations module is optional):
npm install --save #angular/material #angular/cdk
npm install --save #angular/animations
This should add the following lines in package.json:
"#angular/animations": "https://registry.npmjs.org/#angular/animations/-/animations-4.2.5.tgz",
"#angular/cdk": "^2.0.0-beta.8",
"#angular/material": "^2.0.0-beta.8",
You now should try executing webpack build with following command in cmd or PowerShell:
webpack --config webpack.config.vendor.js
If there are no errors you can include the components you want to use in app.module.shared.ts:
// angular material modules
import {
MdAutocompleteModule,
MdButtonModule,
MdButtonToggleModule,
MdCardModule,
MdCheckboxModule,
MdChipsModule,
MdCoreModule,
MdDatepickerModule,
MdDialogModule,
MdExpansionModule,
MdGridListModule,
MdIconModule,
MdInputModule,
MdListModule,
MdMenuModule,
MdNativeDateModule,
MdPaginatorModule,
MdProgressBarModule,
MdProgressSpinnerModule,
MdRadioModule,
MdRippleModule,
MdSelectModule,
MdSidenavModule,
MdSliderModule,
MdSlideToggleModule,
MdSnackBarModule,
MdSortModule,
MdTableModule,
MdTabsModule,
MdToolbarModule,
MdTooltipModule,
} from '#angular/material';
import { CdkTableModule } from '#angular/cdk';
and add them to imports in #NgModule
There are still some components that are bugged until next fixes. Like the checkbox component which breaks server-side rendering when you refresh page. But it will be fixed in the next release (it has been already on master branch).
Using latest Angular Material in ASP.net Core 2.0 with default installed node packages is more difficult and time consuming for resolving package dependencies.
Use below version of angular material in package.json
"#angular/cdk": "^2.0.0-beta.12"
"#angular/material": "^2.0.0-beta.12"
followed by run below command to install it.
npm install --save

react, meteor, webpack, es6. How to create a loading/splash screen

I am using a build for react, es6 modules and meteor with webpack. These techs take a while to load all their stuff, before something shows up on the page. How can I with this stack show a pre-loader / splash screen while all this loads up?
my webpack file:
var autoprefixer = require('autoprefixer');
module.exports = {
entry: [
'babel-polyfill',
'./entry'
],
resolve: {
extensions: ['', '.js', '.jsx', '.json','css','scss']
},
devtool: 'eval',
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel',
exclude: /node_modules/,
query: {
plugins:['transform-runtime'],
presets:['es2015','stage-0','react']
}
},
{
test: /\.scss$/,
loader: 'style-loader!css-loader!sass-loader!postcss-loader'
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'url?limit=8192',
'img-loader'
]
},
]
},
postcss: [ autoprefixer({ browsers: ['last 2 versions'] }) ]
};
My entry.js file:
import '../store.js';
import './../lib/routes.jsx';
My routes.jsx file:
import React from 'react';
import {FlowRouter} from 'meteor/kadira:flow-router';
import {mount} from 'react-mounter';
import $ from 'jquery';
import store from '../store.js';
import {Provider} from 'react-redux';
import App from '../client/components/app/app.jsx';
import HomePage from '../client/components/pages/home/homePage.jsx';
import AboutPage from '../client/components/pages/about/aboutPage.jsx';
import BlogPage from '../client/components/pages/blog/blogPage.jsx';
import BlogPostPage from '../client/components/pages/blogPost/blogPostPage.jsx';
FlowRouter.route('/', {
name:"home",
action() {
mount(App, {page: <Provider store={store}><HomePage /></Provider>});
}
});
FlowRouter.route('/about', {
name:"about",
action() {
mount(App, {page: <Provider store={store}><AboutPage /></Provider>});
}
});
FlowRouter.route('/blog', {
name:"blog",
action() {
mount(App, {page: <Provider store={store}><BlogPage /></Provider>});
}
});
FlowRouter.route('/blog/:slug', {
name:"blog post",
action(params) {
console.log(params);
mount(App, {page: <Provider store={store}><BlogPostPage slug={params.slug} /></Provider>});
}
});
// this is just a work around for a problem I am having with initial rout loading in development mode.
if (!$('.app-root').length)
FlowRouter.go(window.location.href.replace(/^http(s)?\:\/\/[^:\/\#]*(\:[^\/\#]*)?\/?/,'/').replace(/\#.*$/,'')+'#'+Math.floor(Math.random()*100000));
let lastPage = FlowRouter.current();
store.subscribe(()=>{
let state = store.getState();
if (!state || state.currentURL != lastPage)
FlowRouter.go(state.currentURL);
});
After a ton of research and a lot of help from this thread: https://github.com/webpack/webpack/issues/215
I have discovered that there is no reliable way to do this, at least not what I had in mind.
The solution I used in the end was in my entry file to use the following code:
import $ from 'jquery';
$('body').addClass('css-loading-class-goes-here');
require.ensure(['../store.js', './../lib/routes.jsx'], function(require) {
require(['../store.js','./../lib/routes.jsx']);
});
You can add css, append content or whatever else you want to do at the start there, but this will only execute after alot of the 'native' javascript from webpack and friends has loaded (about 350kb in my case). Then the require.ensure enforces webpack to load all my app specific javascript in a seperate bundle after the fact, so my 'loader' is at lest active for half of the load process.
This was the only solution that I could find in the end.

Resources