Skip to content

Instantly share code, notes, and snippets.

@KingDarBoja
Created November 30, 2019 01:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KingDarBoja/591ee28eb1a04ee5bcac7f6906918a0d to your computer and use it in GitHub Desktop.
Save KingDarBoja/591ee28eb1a04ee5bcac7f6906918a0d to your computer and use it in GitHub Desktop.
Sample Webpack Config files on typescript for ngx-charts with AOT
import webpack from 'webpack';
import { CleanWebpackPlugin } from 'clean-webpack-plugin';
import CopyWebpackPlugin from 'copy-webpack-plugin';
import { root } from './helpers';
const WebpackCommonConfig: webpack.Configuration = {
entry: {
polyfills: './app/polyfills.ts',
// vendor: './app/vendor.ts',
app: './app/main.ts',
},
module: {
rules: [
/**
* --- Process component templates ---
* Use **raw-loader** instead of **html-loader** as stated by official Angular Team at
* https://github.com/angular/angular-cli/issues/3415.
*
* Also, this is recommended for the angular2-template-loader as seen on the issue below:
* https://github.com/TheLarkInn/angular2-template-loader/issues/86.
*
* Last, it maintain AOT compilation which will be used for production build.
*/
{
test: /\.html$/,
use: 'html-loader'
},
/**
* --- Process component stylesheets ---
* **to-string-loader** - cast the output css style to a string for Angular components.
*
* Also, the css-loader was not loading properly the url path.
* Check this comment for the implemented fix:
* https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/246#issuecomment-308438193.
*
* EDIT: Looks like these loaders are not working as expected. Use raw-loader in the meantime to
* properly resolve urls.
*/
{
test: /\.css$/,
include: root('app', ''),
use: ['raw-loader'],
},
/**
* --- Process font assets ---
* **file-loader** - resolves import/require() on a file into a url and emits the file
* into the output directory.
*/
{
test: /\.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/'
},
}
]
},
/**
* --- Process image assets ---
* The option name retain the full directory structure.
*/
{
test: /\.(png|jpg?)(\?[a-z0-9]+)?$/,
use: [
{
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
}
}
]
},
/**
* --- Hide Deprecation Warnings ---
* Mark files inside `@angular/core` as using SystemJS style dynamic imports.
* Removing this will cause deprecation warnings to appear.
* Source: https://github.com/angular/angular/issues/21560#issuecomment-433601967
*/
{
test: /[\/\\]@angular[\/\\]core[\/\\].+\.js$/,
parser: { system: true }, // enable SystemJS
}
]
},
plugins: [
// Automatically load modules instead of having to import or require them everywhere.
new webpack.ProvidePlugin({
jQuery: 'jquery',
$: 'jquery',
jquery: 'jquery'
}),
// Fixes this warning -> Critical dependency the request of a dependency is an expression.
// Source: https://github.com/angular/angular/issues/20357#issuecomment-354300874
new webpack.ContextReplacementPlugin(
/angular(\\|\/)core(\\|\/)(@angular|fesm5)/,
root('./src')
),
// Clean dist folder after each build, so that only used files will be generated.
new CleanWebpackPlugin(),
// Include in our dist folder files that would not be included
// by the file-loader or url-loader such as the favicon.
new CopyWebpackPlugin([
{ from: 'app/shared/assets/i18n/*.json', to: '' },
{ from: 'app/**/*.jpg', to: '' },
{ from: 'app/**/*.png', to: '' },
{ from: 'app/**/*.svg', to: '' },
{ from: 'app/**/*.ttf', to: '' }
], {})
],
resolve: {
// Tell Webpack our imports are TypeScript files too.
extensions: ['.ts', '.js']
},
stats: {
warnings: false,
colors: true,
},
optimization: {
// Modules are not shared across entries, so by providing 'runtimeChunk' with 'single' option
// will generate a single runtime.js chunk which is referenced for every module. So lesser code to be downloaded!
runtimeChunk: 'single',
splitChunks: {
// Put everything in node_modules into a file called vendors~main.js
chunks: 'all',
// Now we want to split the node_modules into smaller files per package.
// Check the source code in the article below:
// https://medium.com/hackernoon/the-100-correct-way-to-split-your-chunks-with-webpack-f8a9df5b7758
maxInitialRequests: Infinity,
minSize: 0,
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name(module): string {
// get the name. E.g. node_modules/packageName/not/this/part.js
// or node_modules/packageName
const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
// npm package names are URL-safe, but some servers don't like @ symbols
return `npm.${packageName.replace('@', '')}`;
},
},
},
}
}
};
export default WebpackCommonConfig;
import webpack from 'webpack';
import webpackMerge from 'webpack-merge';
import WebpackCommonConfig from './webpack.common';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import { root } from './helpers';
const WebpackDevConfig: webpack.Configuration = webpackMerge(WebpackCommonConfig, {
mode: 'development',
// Best support for sourcemaps whilst debugging.
devtool: 'cheap-module-eval-source-map',
output: {
path: root('prod'),
publicPath: '/',
filename: '[name].js',
chunkFilename: '[id].chunk.js',
},
module: {
rules: [
/**
* --- Process the TypeScript files ---
* **ts-loader** - TypeScript loader for webpack.
* **angular-router-loader** - loader that enables string-based module loading
* with the Angular Router.
* ***angular2-template-loader** - chain-to loader that inlines all html and styles
* in Angular components.
*/
{
test: /\.tsx?$/,
use: [
{
loader: 'ts-loader',
options: {
configFile: root('tsconfig.dev.json'),
},
},
'angular-router-loader',
'angular2-template-loader',
],
},
/**
* --- Process global stylesheet ---
*
* **NOTE** Do not enable MiniCssExtractPlugin or you will get the same error as below issue
* https://github.com/webpack-contrib/mini-css-extract-plugin/issues/186
*/
{
test: /\.css$/,
exclude: root('app', ''),
use: ['to-string-loader', MiniCssExtractPlugin.loader, 'css-loader'],
},
],
},
plugins: [
// Handles creation of HTML files to serve your webpack bundles.
new HtmlWebpackPlugin({
template: 'app/index.html',
}),
// This plugin extracts CSS into separate files. It creates a CSS file per JS file which contains CSS.
new MiniCssExtractPlugin({
filename: '[name].css',
}),
],
// By default, the dev-server will reload/refresh the page when file changes are detected.
// devServer.hot option must be disabled or devServer.watchContentBase option must be enabled
// in order for liveReload to take effect.
devServer: {
contentBase: root('prod'),
clientLogLevel: 'error',
hot: false,
open: true,
port: 8080,
},
});
export default WebpackDevConfig;
import webpack from 'webpack';
import webpackMerge from 'webpack-merge';
import WebpackCommonConfig from './webpack.common';
import { AngularCompilerPlugin } from '@ngtools/webpack';
import { IndexHtmlWebpackPlugin } from '@angular-devkit/build-angular/src/angular-cli-files/plugins/index-html-webpack-plugin';
import { root } from './helpers';
const WebpackProdConfig: webpack.Configuration = webpackMerge(WebpackCommonConfig, {
mode: 'production',
output: {
path: root('prod'),
publicPath: '',
filename: '[name].[hash].js',
chunkFilename: '[id].[hash].chunk.js',
},
module: {
rules: [
{
test: /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/,
use: '@ngtools/webpack',
},
/**
* --- Process global stylesheet ---
*
* **NOTE** Do not enable MiniCssExtractPlugin or you will get the same error as below issue
* https://github.com/webpack-contrib/mini-css-extract-plugin/issues/186
*/
{
test: /\.css$/,
exclude: root('app', ''),
use: [
'to-string-loader',
// MiniCssExtractPlugin.loader,
'css-loader',
],
},
],
},
plugins: [
/**
* The `@ngtools/webpack` along with `AngularCompilerPlugin` will generate factory files in memory
* so no need to create `main.aot.ts` file.
* Check below link to the post on Stackoverflow referring this:
* https://stackoverflow.com/questions/43810857/ngtools-webpack-missing-app-module-ngfactory
*/
new AngularCompilerPlugin({
entryModule: root('app', 'modules', 'app', 'app.module#AppModule'),
mainPath: root('app', 'main'),
sourceMap: true,
tsConfigPath: root('tsconfig.prod.json'),
skipCodeGeneration: false, // Give you an AOT build that doesn't require the compiler.
}),
new IndexHtmlWebpackPlugin({
input: 'app/index.html',
output: 'index.html',
entrypoints: ['polyfills', 'app'],
}),
],
});
export default WebpackProdConfig;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment