Skip to content

Instantly share code, notes, and snippets.

@BenevidesLecontes
Created February 17, 2018 15:33
Show Gist options
  • Save BenevidesLecontes/6e0e811317d23e78a4fdf43eb5e292a9 to your computer and use it in GitHub Desktop.
Save BenevidesLecontes/6e0e811317d23e78a4fdf43eb5e292a9 to your computer and use it in GitHub Desktop.
const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
const {CommonsChunkPlugin} = require('webpack').optimize;
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const WriteFilePlugin = require('write-file-webpack-plugin');
const proxy = require('http-proxy-middleware'); // require('http-proxy-middleware');
const HtmlWebpackPlugin = require('html-webpack-plugin'); // require('http-proxy-middleware');
const pkg = require('./package.json');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ngToolsWebpack = require('@ngtools/webpack');
const rxPaths = require('rxjs/_esm5/path-mapping');
const nodeModules = path.join(process.cwd(), 'node_modules');
const realNodeModules = fs.realpathSync(nodeModules);
const genDirNodeModules = path.join(process.cwd(), 'src', '$$_gendir', 'node_modules');
const entryPoints = ["inline", "polyfills", "sw-register", "styles", "vendor", "main"];
console.log(process.env.NODE_ENV !== "production", process.env.NODE_ENV);
const aotPlugin = new ngToolsWebpack.AngularCompilerPlugin({
tsConfigPath: process.env.NODE_ENV === "production" ? "tsconfig.aot.json" : "tsconfig.json",
entryModule: path.join(__dirname, "src/app/main.module#WiseitAppModule"),
sourceMap: true,
skipCodeGeneration: process.env.NODE_ENV !== "production"
});
const wiseitVersion = pkg.version;
let localConfig;
try {
localConfig = require('./local.config.json');
} catch (e) {
localConfig = {};
}
const target = 'http://' + (localConfig.host || '192.168.3.139') + ':' + (localConfig.hostPort || '8080');
const jsonPlaceholderProxy = proxy('/wiseit', {
target: target,
changeOrigin: true,
ws: true,
https: false
});
const extractLess = new ExtractTextPlugin({
filename: `[name].${wiseitVersion}.[hash].css`
});
module.exports = () => {
const config = {
context: __dirname,
entry: {
"main": [
"./src/app/main.module.ts"
],
"polyfills": [
"./src/app/polyfills.ts"
],
"styles": [
"./src/app/styles/style.less"
]
},
output: {
path: path.join(process.cwd(), "build/app"),
filename: `[name]-${wiseitVersion}.js?[hash]-[name]`,
chunkFilename: "[id].chunk.js",
crossOriginLoading: false,
publicPath: path.resolve(__dirname, '/')
},
watchOptions: {
poll: true
},
resolve: {
// Add '.ts' and '.tsx' as a resolvable extension.
modules: [
path.resolve(__dirname, 'node_modules'),
path.resolve(__dirname, 'node_modules'),
],
extensions: [".webpack.js", ".web.js", ".js", ".ts", '.css', ".json", '.less', ".tsx", ".html"],
alias: rxPaths()
},
module: {
rules: [
{
test: /\.html$/, loader: 'html-loader',
options: {
ignoreCustomFragments: [/{{.*?}}/],
minimize: true,
removeComments: true,
collapseWhitespace: true,
// angular 2 templates break if these are omitted
removeAttributeQuotes: false,
keepClosingSlash: true,
caseSensitive: true,
conservativeCollapse: true
}
},
{
test: /\.css$/
// ExtractTextPlugin CANNOT BE USED WITH AOT BUILD,
// because it does not support ChildCompilation
// ... "ExtractTextPlugin used without corresponding plugin"-error
// So for the component css files use normal loader
, use: ['css-to-string-loader'].concat('css-loader')
},
{
test: /\.less$/,
include: path.resolve(__dirname, 'src/app/styles'),
use: ['css-to-string-loader'].concat(ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {url: false}
},
{loader: 'autoprefixer-loader'},
{
loader: 'less-loader',
options: {relativeUrls: false}
}]
}))
}, {
"test": /\.(jpg|png|webp|gif|otf|ttf|woff|woff2|ani)$/,
"loader": "url-loader",
"options": {
"name": "[name].[hash:20].[ext]",
"limit": 10000
}
},
{
"test": /\.(eot|svg|cur)$/,
"loader": "file-loader",
"options": {
"name": "[name].[hash:20].[ext]",
"limit": 10000
}
},
],
},
plugins: [
extractLess,
aotPlugin,
new webpack.ContextReplacementPlugin(
// The (\\|\/) piece accounts for path separators for Windows and MacOS
/(.+)?angular([\\/])core(.+)?/,
path.join(__dirname, './src'), // location of your src
{} // a map of your routes
),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
'window.jQuery': 'jquery',
'window.$': 'jquery',
_: 'lodash',
Selectize: "Selectize",
selectize: "Selectize",
DataTable: "DataTable",
dataTable: "DataTable"
}),
new WriteFilePlugin(),
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'src/app/index.html',
inject: true,
"hash": false,
"compile": true,
"favicon": false,
"minify": false,
"cache": true,
"showErrors": true,
"chunks": "all",
"excludeChunks": [],
"title": "Webpack App",
"xhtml": true,
"chunksSortMode": function sort(left, right) {
let leftIndex = entryPoints.indexOf(left.names[0]);
let rightindex = entryPoints.indexOf(right.names[0]);
if (leftIndex > rightindex) {
return 1;
}
else if (leftIndex < rightindex) {
return -1;
}
else {
return 0;
}
}
}),
new CommonsChunkPlugin({
"name": [
"inline"
],
"minChunks": null
}),
new CommonsChunkPlugin({
"name": [
"vendor"
],
"minChunks": (module) => {
return module.resource
&& (module.resource.startsWith(nodeModules)
|| module.resource.startsWith(genDirNodeModules)
|| module.resource.startsWith(realNodeModules));
},
"chunks": [
"main"
]
}),
new webpack.SourceMapDevToolPlugin({
"filename": "[file].map[query]",
"moduleFilenameTemplate": "[resource-path]",
"fallbackModuleFilenameTemplate": "[resource-path]?[hash]",
"sourceRoot": "webpack:///"
}),
new CommonsChunkPlugin({
"name": [
"main"
],
"minChunks": 2,
"async": "common"
}),
new webpack.NamedModulesPlugin({}),
new webpack.NoEmitOnErrorsPlugin(),
new ForkTsCheckerWebpackPlugin({
// tslint: true,
workers: 2
}),
new webpack.DefinePlugin({
'process.env': {
'ENV': JSON.stringify(process.env.NODE_ENV)
}
}),
new webpack.LoaderOptionsPlugin({
htmlLoader: {
minimize: false // workaround for ng2
}
})
],
externals: {
// shows how we can rely on browser globals instead of bundling these dependencies,
// in case we want to access jQuery from a CDN or if we want an easy way to
// avoid loading all moment locales: https://github.com/moment/moment/issues/1435
angular: 'angular',
jquery: 'jQuery',
moment: 'moment',
Fullcalendar: 'Fullcalendar',
DataTable: 'DataTable',
Selectize: 'Selectize'
},
devServer: {
historyApiFallback: true,
contentBase: [path.resolve(__dirname, 'src/app'),
path.resolve(__dirname, 'build/app'), path.resolve(__dirname, 'build')],
publicPath: path.resolve(__dirname, '/'),
watchOptions: {
aggregateTimeout: 300,
poll: 1000
},
watchContentBase: true,
host: (localConfig.connect || '0.0.0.0'),
port: localConfig.port || 9000,
proxy: {
'/wiseit': {
target: target,
changeOrigin: true,
ws: true,
https: false
}
}
},
"node": {
"fs": "empty",
"global": true,
"crypto": "empty",
"tls": "empty",
"net": "empty",
"process": true,
"module": false,
"clearImmediate": false,
"setImmediate": false
},
};
if (process.env.NODE_ENV === "production") {
config.plugins.push(new webpack.optimize.UglifyJsPlugin({ // https://github.com/angular/angular/issues/10618
beautify: false,
comments: false,
compress: {
screw_ie8: true,
warnings: false
},
mangle: {
keep_fnames: true,
screw_i8: true
}
}));
config.module.rules.push({
test: /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/,
loader: '@ngtools/webpack'
});
} else {
config.module.rules.push({
test: /\.tsx?$/,
use: [
{
loader: 'ts-loader',
options: {
transpileOnly: true
}
}
]
});
}
return config;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment