Using Webpack 2 and extract-text-webpack-plugin - javascript

I'm using extract-text-webpack-plugin 2.0.0-rc.3 with Webpack 2.2.1 and am getting this error when running the build:
/node_modules/extract-text-webpack-plugin/index.js:259
var shouldExtract = !!(options.allChunks || chunk.isInitial());
^
TypeError: chunk.isInitial is not a function
Here is my webpack.config.js:
'use strict';
const argv = require('yargs').argv;
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const webpack = require('webpack');
module.exports = (function () {
let config = {
entry : './' + process.env.npm_package_config_paths_source + '/main.js',
output : {
filename : 'main.js'
},
watch : !!argv.watch,
vue : {
loaders : {
js : 'babel-loader',
// Create separate CSS file to prevent unstyled content
sass : ExtractTextPlugin.extract("css!sass?sourceMap") // requires `devtool: "#source-map"`
}
},
module : {
rules : [
{
test : /\.js$/,
use : 'babel-loader',
exclude : '/node_modules/'
},
{
test : /\.vue$/,
use : 'vue-loader',
options : {
loaders : {
'scss' : 'vue-style-loader!css-loader!sass-loader',
'sass' : 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
},
}
}
]
},
plugins : [
new webpack.DefinePlugin({
'process.env' : {
npm_package_config_paths_source : '"' + process.env.npm_package_config_paths_source + '"'
}
}),
new ExtractTextPlugin("style.css")
],
resolve : {
alias : {
'vue$' : 'vue/dist/vue.common.js'
}
},
babel : {
"presets" : ["es2015", "stage-2"],
"comments" : false,
"env" : {
"test" : {
"plugins" : ["istanbul"]
}
}
},
devtool : "#source-map" // #eval-source-map is faster but not compatible with ExtractTextPlugin
};
if (process.env.NODE_ENV === 'production') {
config.plugins = [
// short-circuits all Vue.js warning code
new webpack.DefinePlugin({
'process.env' : {
NODE_ENV : '"production"',
npm_package_config_paths_source : '"' + process.env.npm_package_config_paths_source + '"'
}
}),
// minify with dead-code elimination
new webpack.optimize.UglifyJsPlugin(),
new ExtractTextPlugin("style.css")
];
config.devtool = "#source-map";
}
return config;
})();
When I remove new ExtractTextPlugin("style.css") from the plugins array the build runs fine, but doesn't create style.css.
If I add the allChunks: true option the error becomes this:
/node_modules/webpack/lib/Chunk.js:80
return this.entrypoints.length > 0;
^
TypeError: Cannot read property 'length' of undefined

In case you are writing style rules in .vue file or seprate .scss file, with below webpack configurations you can achieve what you're searching for:
webpack.confi.js:
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
....
....
module.exports = {
....
....
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
'scss': ExtractTextPlugin.extract('css-loader!sass-loader'),
'sass': ExtractTextPlugin.extract('css-loader!sass-loader?indentedSyntax')
}
}
},
....
....
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('css-loader!sass-loader')
}
....
....
] // rules end
}, // module end
plugins: [
new ExtractTextPlugin('style.css')
],
....
}
Just make sure that you have installed these modules/loaders via NPM:
css-loader
sass-loader
node-sass
extract-text-webpack-plugin

Related

React: Read configurations from external file

I'm trying to implement a solution for reading configurations from some file in my react app... don't know what is the best practice but I adapted the following way and tried implementing it:
1) under the root of my app (in parallel to webpack.config.js)
I created a file called: config.dev.json with this content:
{
"protocol" : "http",
"host" : "localhost",
"port" : "8080"
}
2) to webpack.config.js added my code (TODO part at the end):
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const rtlcss = require('rtlcss');
const webpack = require("webpack");
const useExternalCss =
process.env.CARBON_REACT_STORYBOOK_USE_EXTERNAL_CSS === 'true';
const useStyleSourceMap =
process.env.CARBON_REACT_STORYBOOK_USE_STYLE_SOURCEMAP === 'true';
const useRtl = process.env.CARBON_REACT_STORYBOOK_USE_RTL === 'true';
const styleLoaders = [
{
loader: 'css-loader',
options: {
importLoaders: 2,
sourceMap: useStyleSourceMap,
},
},
{
loader: 'postcss-loader',
options: {
plugins: () => {
const autoPrefixer = require('autoprefixer')({
browsers: ['last 1 version', 'ie >= 11'],
});
return !useRtl ? [autoPrefixer] : [autoPrefixer, rtlcss];
},
sourceMap: useStyleSourceMap,
},
},
{
loader: 'sass-loader',
options: {
includePaths: [path.resolve(__dirname, '..', 'node_modules')],
data: `
$feature-flags: (
ui-shell: true,
);
`,
sourceMap: useStyleSourceMap,
},
},
];
module.exports = (baseConfig, env, defaultConfig) => {
defaultConfig.devtool = useStyleSourceMap ? 'source-map' : '';
defaultConfig.optimization = {
...defaultConfig.optimization,
minimizer: [
new TerserPlugin({
sourceMap: true,
terserOptions: {
mangle: false,
},
}),
],
};
defaultConfig.module.rules.push({
test: /-story\.jsx?$/,
loaders: [
{
loader: require.resolve('#storybook/addon-storysource/loader'),
options: {
prettierConfig: {
parser: 'babylon',
printWidth: 80,
tabWidth: 2,
bracketSpacing: true,
trailingComma: 'es5',
singleQuote: true,
},
},
},
],
enforce: 'pre',
});
defaultConfig.module.rules.push({
test: /\.scss$/,
sideEffects: true,
use: [
{ loader: useExternalCss ? MiniCssExtractPlugin.loader : 'style-loader' },
...styleLoaders,
],
});
if (useExternalCss) {
defaultConfig.plugins.push(
new MiniCssExtractPlugin({
filename: '[name].[contenthash].css',
})
);
}
//TODO
if (!defaultConfig.resolve) {
defaultConfig.resolve = {};
}
if (!defaultConfig.resolve.alias) {
defaultConfig.resolve.alias = {};
}
defaultConfig.resolve.alias.Config = process.env.NODE_ENV === 'production'
? path.resolve('./config.prod.json')
: path.resolve('./config.dev.json');
return defaultConfig;
};
module.exports = {
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('development'),
'BASE_URL': JSON.stringify('http://localhost:3000/')
}
})
],
// externals: {
// 'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? require('./config.prod.json') : require('./config.dev.json'))
// }
//
// // externals: {
// // 'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? {
// // serverUrl: "http://test.com:8080"
// // } : {
// // serverUrl: "http://localhost:8080"
// // })
// // }
//
}
3) and tried to use it from some component that way:
let Config = require('Config')
but I'm getting:
./src/stores/RestService.js
Module not found: Can't resolve 'Config' in 'C:
If you want to setup configuration without webpack (e.g. when using create-react-app) this is how I'd suggest:
Create config folder (or name it however you want) and add your config files and index file:
config.dev.json
config.prod.json
index.js
And then inside your config/index.js file:
if (process.env.NODE_ENV === 'development') {
module.exports = require('./config.dev.json')
} else {
module.exports = require('./config.prod.json')
}
Use it with import config from './config';
why not use like this
at your package.json
"scripts": {
"develop": "PORT=8080 HOST=localhost PROTOCOL=http node ."
"production": "Your config here"
}
create a config/app.js
const config = process.env
module.export = {
port: config.PORT,
protocol: config.PROTOCOL,
host: config.HOST,
}
In your webpack ( actually, i don't know why you have to import config in your webpack and reexport it. if you want your jsx or js files able to read the PORT, HOST, and LOCALHOST, u can just follow until step 2, and u can freely get your config files in any your app.js files )
const config = require('./path/to/config/app.js')
module.exports = {
externals: {
config: config,
}
}
First you need the configuration file in your bundle, it's not an external (so we only need to remove the external part).
Then you need the config file to be resolved as a diffrent file depending on the environment (prod or dev, using resolve.alias).
Be carefull of the working directory too, either run webpack from the project's folder, or use the context configuration option.
Suggested webpack config (relevant part in the end):
module.exports = (baseConfig, env, defaultConfig) => {
defaultConfig.devtool = useStyleSourceMap ? 'source-map' : '';
defaultConfig.optimization = {
...defaultConfig.optimization,
minimizer: [
new TerserPlugin({
sourceMap: true,
terserOptions: {
mangle: false,
},
}),
],
};
defaultConfig.module.rules.push({
test: /-story\.jsx?$/,
loaders: [
{
loader: require.resolve('#storybook/addon-storysource/loader'),
options: {
prettierConfig: {
parser: 'babylon',
printWidth: 80,
tabWidth: 2,
bracketSpacing: true,
trailingComma: 'es5',
singleQuote: true,
},
},
},
],
enforce: 'pre',
});
defaultConfig.module.rules.push({
test: /\.scss$/,
sideEffects: true,
use: [
{ loader: useExternalCss ? MiniCssExtractPlugin.loader : 'style-loader' },
...styleLoaders,
],
});
defaultConfig.module.rules.push({
test: /\.json$/,
use: [
{ loader: useExternalCss ? MiniCssExtractPlugin.loader : 'style-loader' },
...styleLoaders,
],
});
if (useExternalCss) {
defaultConfig.plugins.push(
new MiniCssExtractPlugin({
filename: '[name].[contenthash].css',
})
);
}
// ensure resolve alias present in the config
if (!defaultConfig.resolve) {
defaultConfig.resolve = {};
}
if (!defaultConfig.resolve.alias) {
defaultConfig.resolve.alias = {};
}
// resolve the alias to the right config file according to NODE_ENV
// you'll have to correctly set <relative path to your config>
defaultConfig.resolve.alias.Config = process.env.NODE_ENV === 'production'
? path.resolve(__dirname, '<relative path to your config>/config.prod.json')
: path.resolve(__dirname, '<relative path to your config>/config.dev.json');
return defaultConfig;
};
don't forget to remove this:
module.exports = {
externals: {
'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? require('./config.prod.json') : require('./config.dev.json'))
}
// externals: {
// 'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? {
// serverUrl: "http://test.test.com:8080"
// } : {
// serverUrl: "http://localhost:8080"
// })
// }
}
As it will prevent webpack from bundling the file.
You can use DefinePlugin to define setting config in webpack like this
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('development'),
'BASE_URL': JSON.stringify('http://localhost:5000/')
}
})
],
Then simply use
process.env.BASE_URL
or
process.env.NODE_ENV

Webpack Module not found when importing Typescript

I am currently converting a project to use Webpack for bundling.
In my Typescript files I am importing modules as bellow, and am getting no errors as well as intelisense.
import * as $ from "jquery";
import * as CrudHelper from "../../ts-helpers/crud-helper";
import { ExportToExcel } from "../../ts-helpers/export-helper";
import { getParameterByName } from "../../ts-helpers/utils";
This was working with webpack however it turned out that the transpiled JS files created by visual studio were still hanging around and I had turned typescript compilation off.
After deleting the js files, when I run my webpack.config, I am getting module not found errors like
Module not found: Error: Can't resolve '../../ts-helpers/crud-helper' in 'C:\Users\alexl\git\eServicesWebpack\eServices\src\eServices.Web\Client\ts\Areas\Employee'
# ./Client/ts/Areas/Employee/Absence.ts 4:17-56
# multi ./Client/ts/Areas/Employee/Absence.ts
My tsconfig looks like
{
"compilerOptions": {
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"target": "es5",
"allowJs": true
},
"exclude": [
"node_modules",
"wwwroot",
"typings"
]
}
Is there something missing from my tsconfig?
Edit
This is my webpack.config
var webpack = require('webpack');
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var glob = require('glob');
var files = glob.sync("./Client/ts/Areas/**/*.ts");
var entry = {
'vendor': "./Client/ts/Vendor.ts"
}
files.forEach(function (e) {
var split = e.split('/');
var entryName = "";
if (split[5].indexOf('Modal') > -1) {
entryName = split[4] + '/' + split[5].split('.')[0].replace('Modal', '') + '/' + split[5].split('.')[0];
} else {
entryName = split[4] + '/' + split[5].split('.')[0].replace('Modal', '') + '/' + split[5].split('.')[0].replace('Modal', '');
}
if (entry[entryName] === undefined) {
entry[entryName] = [];
}
entry[entryName].push(e);
});
module.exports = function () {
return {
entry: entry,
output: {
path: path.resolve(__dirname, "../wwwroot/dist"),
filename: "[name].bundle.js"
},
plugins: [
//chunk vendor code into own bundle
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: function (module) {
return module.context && module.context.indexOf('node_modules') !== -1;
}
}),
//chunk webpack runtime code co vendor code can be cached
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest'
}),
new ExtractTextPlugin('styles.css'),
//protect against old libraries that reference jquery symbols
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
],
module: {
rules: [
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
use: 'css-loader'
})
},
{
test: /\.ts$/,
use: "awesome-typescript-loader"
},
{
test: /\.(jpg|png|gif)$/,
use: 'file-loader'
}, {
test: /\.(woff|woff2|eot|ttf|svg)$/,
use: {
loader: 'url-loader',
options: {
limit: 100000
}
}
}
]
}
}
};
Add '.ts' as resolvable extensions.
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx']
}
Are you using any loader for your ts file in webpack.config file? You should have something like this
module:{
loaders:[
{
test: /\.tsx?$/,
loader: 'ts-loader'
},
]
}
Update from Comments:
resolve: {
// Add '.ts' as resolvable extensions.
extensions: ["", ".webpack.js", ".web.js", ".ts", ".js"]
}

How to use postcss (lost grid) in vue-loader

I'm experimenting with Vue2 and have a question on using lost-grid (http://lostgrid.org/) in my app. Lost-grid is a postcss grid-system and I've been able to use this numerous times in react apps with webpack2.
How can I use lost-grid i with vue-loader? I've installed 'lost' through npm, and tried different ways of adding the postcss loader. Nothing seems to work and the documentation isn't very helpful either.
Here is the business part of webpack.base.conf.js (as I undersrtand it, all the css loading is run through the vue-loader):
module: {
rules: [
{
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: "pre",
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter')
}
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
...
vue-loader.conf.js looks like:
var utils = require('./utils')
var config = require('../config')
var isProduction = process.env.NODE_ENV === 'production'
module.exports = {
loaders: utils.cssLoaders({
sourceMap: isProduction
? config.build.productionSourceMap
: config.dev.cssSourceMap,
extract: isProduction
})
}
utils.js looks like this:
var path = require('path')
var config = require('../config')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
exports.assetsPath = function (_path) {
var assetsSubDirectory = process.env.NODE_ENV === 'production'
? config.build.assetsSubDirectory
: config.dev.assetsSubDirectory
return path.posix.join(assetsSubDirectory, _path)
}
exports.cssLoaders = function (options) {
options = options || {}
var cssLoader = {
loader: 'css-loader',
options: {
minimize: process.env.NODE_ENV === 'production',
sourceMap: options.sourceMap
}
}
// generate loader string to be used with extract text plugin
function generateLoaders (loader, loaderOptions) {
var loaders = [cssLoader]
if (loader) {
loaders.push({
loader: loader + '-loader',
options: Object.assign({}, loaderOptions, {
sourceMap: options.sourceMap
})
})
}
// Extract CSS when that option is specified
// (which is the case during production build)
if (options.extract) {
return ExtractTextPlugin.extract({
use: loaders,
fallback: 'vue-style-loader'
})
} else {
return ['vue-style-loader'].concat(loaders)
}
}
// http://vuejs.github.io/vue-loader/en/configurations/extract-css.html
return {
css: generateLoaders(),
postcss: generateLoaders(''),
less: generateLoaders('less'),
sass: generateLoaders('sass', { indentedSyntax: true }),
scss: generateLoaders('sass'),
stylus: generateLoaders('stylus'),
styl: generateLoaders('stylus')
}
}
// Generate loaders for standalone style files (outside of .vue)
exports.styleLoaders = function (options) {
var output = []
var loaders = exports.cssLoaders(options)
for (var extension in loaders) {
var loader = loaders[extension]
output.push({
test: new RegExp('\\.' + extension + '$'),
use: loader
})
}
return output
}
Question now is... where do I put what? Any help would be greatly appreciated.
add the following lines to the vue-loader.config.js file in build/
postcss: [
require('autoprefixer')({
browsers: ['last 7 versions']
})
]
so it looks like this:
module.exports = {
loaders: utils.cssLoaders({
sourceMap: isProduction ? config.build.productionSourceMap : config.dev.cssSourceMap,
extract: isProduction
}),
postcss: [
require('autoprefixer')({
browsers: ['last 7 versions']
})
]
}
require('lost') should add to the postcss Array like above
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
]
In package.json have define, you can see https://github.com/ai/browserslist#config-file

Webpack2 Error - Module Not Found

I am getting this error:
ERROR in ./~/react/react.js
Module not found: Error: Can't resolve './lib/React' in '/var/www/homelyfe/hl-app/node_modules/react'
# ./~/react/react.js 3:17-39
# ./app/index.js
ERROR in ./~/react-dom/index.js
Module not found: Error: Can't resolve './lib/ReactDOM' in '/var/www/homelyfe/hl-app/node_modules/react-dom'
# ./~/react-dom/index.js 3:17-42
# ./app/index.js
In my index.js (which webpack2 seems to be picking up correctly), when I do
import React from "react";
import { render } from "react-dom";
I get the above error. It seems, webpack is unable to find react. I have react & react-dom dependencies installed in package.json.
My webpack.config.js is:
const path = require("path");
const merge = require("webpack-merge");
const parts = require( "./webpack.config.parts" );
const PATHS = {
app : path.join( __dirname, "app" ),
build : path.join( __dirname, "build" )
};
const common = {
entry : {
app : "./app/index.js"
},
output : {
filename : "run.build.js",
path : PATHS.build
},
resolve : {
alias : {
assets : path.resolve( __dirname, "app/assets" ),
components : path.resolve( __dirname, "app/components" )
},
extensions : [ "js", "jsx" ]
}
};
var config;
switch( process.env.npm_lifecycle_event ){
case( "build-Prod" ): {
...
}
case( "start-Dev" ):
default: {
const eslintPath = path.join( __dirname, "/.eslintrc" );
config = merge( common,
parts.eslint( PATHS.app, eslintPath ),
parts.babel( PATHS.app ),
parts.devServer( PATHS.app ),
parts.htmlWebpackPlugin());
}
}
module.exports = config;
The webpack.config.parts file is:
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
exports.babel = function( path ){
var standardPresets = [
"react",
"es2015"
];
var presets;
presets = standardPresets;
}
return({
module: {
rules : [
{
test : /\.jsx?$/,
include : path,
use : [
{
loader: "babel-loader",
options : {
presets
}
}
]
}
]
}
});
};
exports.devServer = function() {
return ({
devServer: {
historyApiFallback: true,
hot: true,
inline: true,
stats: "errors-only"
},
plugins: [
new webpack.HotModuleReplacementPlugin({
multiStep: true
})
]
});
};
exports.eslint = function( path, configFilePath ){
return ({
module: {
rules : [
{
test : /\.jsx?$/,
enforce : "pre",
include : path,
use : [
{
loader : "eslint-loader",
options : {
configFile : configFilePath
}
}
]
}
]
}
});
};
exports.htmlWebpackPlugin = function( ) {
return ({
plugins: [
new HtmlWebpackPlugin({
title: "title"
})
]
});
};
I was having the same error a few moments ago. After espending a lot of time, I found the solution.
In your resolve.extensions note that the extensions includes the leading dots. In that way you have to replace it with the following:
extensions : [ ".js", ".jsx" ]
Changing that, your problem should be fixed.

Why is webpack creating output js in form of string and using eval function to deploy it?

My webpack.config.js file is as follows:
var path = require('path');
var webpack = require('webpack');
var CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;
var autoprefixer = require('autoprefixer');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var ENV = process.env.npm_lifecycle_event;
var isTest = ENV === 'test' || ENV === 'test-watch';
var isProd = ENV === 'build';
module.exports = function makeWebpackConfig() {
var config = {};
if (isTest) {
config.devtool = 'inline-source-map';
} else if (isProd) {
config.devtool = 'source-map';
} else {
config.devtool = 'eval-source-map';
}
config.debug = !isProd || !isTest;
config.entry = isTest ? {} : {
'vendor': './src/vendor.ts',
'app': './src/bootstrap.ts' // our angular app
};
config.output = isTest ? {} : {
path: root('../edu_analytics_prod_front/dist'),
publicPath: isProd ? '/' : '/',
filename: isProd ? 'js/[name].[hash].js' : 'js/[name].js',
chunkFilename: isProd ? '[id].[hash].chunk.js' : '[id].chunk.js'
};
config.resolve = {
cache: !isTest,
root: root(),
extensions: ['', '.ts', '.js', '.json', '.css', '.scss', '.html'],
alias: {
'app': 'src/client',
'common': 'src/common'
}
};
config.module = {
preLoaders: isTest ? [] : [{test: /\.ts$/, loader: 'tslint'}],
loaders: [
// Support for .ts files.
{
test: /\.ts$/,
loader: 'ts',
query: {
'ignoreDiagnostics': [
2403, // 2403 -> Subsequent variable declarations
2300, // 2300 -> Duplicate identifier
2374, // 2374 -> Duplicate number index signature
2375, // 2375 -> Duplicate string index signature
2502 // 2502 -> Referenced directly or indirectly
]
},
exclude: [isTest ? /\.(e2e)\.ts$/ : /\.(spec|e2e)\.ts$/, /node_modules\/(?!(ng2-.+))/]
},
{test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/, loader: 'file?name=fonts/[name].[hash].[ext]?'},
{test: /\.json$/, loader: 'json'},
{
test: /\.css$/,
exclude: root('src', 'client'),
loader: isTest ? 'null' : ExtractTextPlugin.extract('style', 'css?sourceMap!postcss')
},
// all css required in src/client files will be merged in js files
{test: /\.css$/, include: root('src', 'client'), loader: 'raw!postcss'},
{
test: /\.scss$/,
exclude: root('src', 'client'),
loader: isTest ? 'null' : ExtractTextPlugin.extract('style', 'css?sourceMap!postcss!sass')
},
{test: /\.scss$/, exclude: root('src', 'style'), loader: 'raw!postcss!sass'},
{test: /\.html$/, loader: 'raw'}
],
postLoaders: [],
noParse: [/.+angular2\/bundles\/.+/]
};
if (isTest) {
config.module.postLoaders.push({
test: /\.(js|ts)$/,
include: path.resolve('src'),
loader: 'istanbul-instrumenter-loader',
exclude: [/\.spec\.ts$/, /\.e2e\.ts$/, /node_modules/]
})
}
config.plugins = [
new webpack.DefinePlugin({
'process.env': {
ENV: JSON.stringify(ENV)
}
})
];
if (!isTest) {
config.plugins.push(
new CommonsChunkPlugin({
name: ['vendor', 'polyfills']
}),
new HtmlWebpackPlugin({
template: './src/public/index.html',
inject: 'body',
chunksSortMode: packageSort(['polyfills', 'vendor', 'app'])
}),
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false }
}),
new ExtractTextPlugin('css/[name].[hash].css', {disable: !isProd})
);
}
if (isProd) {
config.plugins.push(
new webpack.NoErrorsPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false }
}),
new CopyWebpackPlugin([{
from: root('src/public')
}])
);
}
config.postcss = [
autoprefixer({
browsers: ['last 2 version']
})
];
config.sassLoader = {
//includePaths: [path.resolve(__dirname, "node_modules/foundation-sites/scss")]
};
config.tslint = {
emitErrors: false,
failOnHint: false
};
config.devServer = {
contentBase: './src/public',
historyApiFallback: true,
stats: 'minimal' // none (or false), errors-only, minimal, normal (or true) and verbose
};
return config;
}();
function root(args) {
args = Array.prototype.slice.call(arguments, 0);
return path.join.apply(path, [__dirname].concat(args));
}
function rootNode(args) {
args = Array.prototype.slice.call(arguments, 0);
return root.apply(path, ['node_modules'].concat(args));
}
function packageSort(packages) {
var len = packages.length - 1;
var first = packages[0];
var last = packages[len];
return function sort(a, b) {
if (a.names[0] === first) {
return -1;
}
if (a.names[0] === last) {
return 1;
}
if (a.names[0] !== first && b.names[0] === last) {
return -1;
} else {
return 1;
}
}
}
When I'm running command like webpack / webpack -p
It is creating three files as follows:
But all three files has output as string and using eval function to deploy it and one file has very big size(7 MB) as follows.
I want simple JavaScript file without eval used inside it as all other common minification library works and I want to reduce size of vendor file as well.
Your config uses this configuration as default:
config.devtool = 'eval-source-map';
The fine manual states:
eval-source-map - Each module is executed with eval and a SourceMap is added as DataUrl to the eval.
If you don't want that, use another devtool option.
As for decreasing code size, you probably want to either disable the creation of a source map entirely (just don't set the devtool option) or have Webpack write the source map to a separate file (devtool : 'source-map' or devtool : 'cheap-source-map', AFAIK).
Also set the NODE_ENV environment variable to production if you want less code:
# if you're on a Unix-like OS:
env NODE_ENV=production webpack -p

Categories