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
Related
I am getting this error when logging into our dev site. This is a part of our migration from .NET framework 4.5.2 to 4.7.2. Though I do not think that has much to do with it. If we publish straight from VS, the page loads fine. If it uses our pipeline, or we did not clear our dirs beforehand, we get this error (in the console browser).
ie-polyfill_aurelia-bootstrapper:1 Uncaught ReferenceError:
webpack_require is not defined
at eval (ie-polyfill_aurelia-bootstrapper:1)
at Object.0 (xxxAppScripts?v=sRzkW2d1FsbC87Brht0ZS8CXZDQaGBaky9ddApOJOaY1:1)
at t (xxxAppScripts?v=sRzkW2d1FsbC87Brht0ZS8CXZDQaGBaky9ddApOJOaY1:1)
at xxxAppScripts?v=sRzkW2d1FsbC87Brht0ZS8CXZDQaGBaky9ddApOJOaY1:1
at xxxAppScripts?v=sRzkW2d1FsbC87Brht0ZS8CXZDQaGBaky9ddApOJOaY1:1
The process of our build should be exactly the same as building with NPM locally, and there are no errors given in the build process. Build is defined for both in the webpack.config.js as follows
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const { AureliaPlugin, ModuleDependenciesPlugin } = require('aurelia-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const { ProvidePlugin, SourceMapDevToolPlugin } = require('webpack')
const { TsConfigPathsPlugin, CheckerPlugin } = require('awesome-typescript-loader');
const CleanWebpackPlugin = require('clean-webpack-plugin');
// config helpers:
const ensureArray = (config) => config && (Array.isArray(config) ? config : [config]) || []
const when = (condition, config, negativeConfig) =>
condition ? ensureArray(config) : ensureArray(negativeConfig)
// primary config:
const title = 'XXXXXX';
const outDir = path.resolve(__dirname, 'Scripts', 'pub');
const srcDir = path.resolve(__dirname, 'App');
const nodeModulesDir = path.resolve(__dirname, 'node_modules');
const baseUrl = '/';
var isDevBuild = true;
var dev;
if (process.env.NODE_ENV) {
dev = process.env.NODE_ENV.trim();
if (dev === "production") {
isDevBuild = true;
}
}
const cssRules = [
{ loader: 'css-loader' },
{
loader: 'postcss-loader',
options: { plugins: () => [require('autoprefixer')({ browsers: ['last 2 versions'] })] }
},
'sass-loader'
];
module.exports = ({ production, server, extractCss, coverage } = {}) => ({
resolve: {
extensions: ['.ts', '.js'],
modules: [srcDir, 'node_modules'],
plugins: [
new TsConfigPathsPlugin(),
],
alias: {
// Enforce single aurelia-binding, to avoid v1/v2 duplication due to
// out-of-date dependencies on 3rd party aurelia plugins
'aurelia-binding': path.resolve(__dirname, 'node_modules/aurelia-binding'),
'aurelia-bootstrapper': path.resolve(__dirname, 'node_modules/aurelia-bootstrapper')
}
},
entry: {
app: ['./ie-polyfill', 'aurelia-bootstrapper'],
vendor: ['jquery'],
},
output: {
path: outDir,
publicPath: baseUrl,
filename: production ? '[name].[chunkhash].bundle.js' : '[name].[hash].bundle.js',
sourceMapFilename: production ? '[name].[chunkhash].bundle.map' : '[name].[hash].bundle.map',
chunkFilename: production ? '[chunkhash].chunk.js' : '[hash].chunk.js',
},
devServer: {
contentBase: baseUrl,
// serve index.html for all 404 (required for push-state)
historyApiFallback: '/',
},
module: {
rules: [
{
test: /\.css$/i,
issuer: [{ not: [{ test: /\.html$/i }] }],
use: extractCss ? ExtractTextPlugin.extract({
fallback: 'style-loader',
use: cssRules,
}) : ['style-loader', ...cssRules],
},
{
test: /\.css$/i,
issuer: [{ test: /\.html$/i }],
// CSS required in templates cannot be extracted safely
// because Aurelia would try to require it again in runtime
use: cssRules,
},
{
test: /\.scss$/,
exclude: /node_modules/,
use: ExtractTextPlugin.extract({
use: ['css-loader', 'sass-loader']
})
},
{ test: /\.html$/i, loader: 'html-loader' },
{ test: /\.ts$/i, loader: 'awesome-typescript-loader', exclude: nodeModulesDir },
{
test: require.resolve("jquery"),
use: [
{
loader: "expose-loader",
options: "$"
}
]
}
]
},
plugins: [
new CleanWebpackPlugin(),
// required polyfills for non-evergreen browsers
new ProvidePlugin({
Map: 'core-js/es6/map',
WeakMap: 'core-js/es6/weak-map',
Promise: 'core-js/es6/promise',
regeneratorRuntime: 'regenerator-runtime' // to support await/async syntax
}),
new AureliaPlugin({
aureliaApp: 'main'
}),
new ProvidePlugin({
'$': 'jquery',
'jQuery': 'jquery',
'window.jQuery': 'jquery',
}),
new CheckerPlugin(),
new ExtractTextPlugin({
filename: production ? '[contenthash].css' : 'style-[id].css',
allChunks: true,
}),
].concat(isDevBuild ? [
new SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(outDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
new UglifyJsPlugin()
]),
})
There do seem to be a few times a similar question has been asked, but there has not been a solution that worked. Thanks for any help provided.
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
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"]
}
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
I started using webpack with my existing project and the bundle it generates is much bigger in size than before webpack.
I am using all the optimisations I can think of and still it's around 60% bigger than before.
I don't know what I am doing wrong.
my config:
'use strict';
// Modules
var webpack = require('webpack');
var autoprefixer = require('autoprefixer');
var HtmlWebpackPlugin = require('html-webpack-plugin');
//var jQueryPlugin = require('jquery');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
//var Promise = require('es6-promise-polyfill').Promise;
module.exports = function makeWebpackConfig (options) {
/**
* BUILD is for generating minified builds
*/
var BUILD = !!options.BUILD;
var config = {};
config.entry = {
app: './app.js',
iosCordova: ['./static/wrapper-resources/js/ios/cordova_all.js'],
androidCordova: ['./static/wrapper-resources/js/android/cordova_all.js']
};
/**
* Output
*/
config.output = {
// Absolute output directory
path: __dirname + '/public',
// Output path from the view of the page
// Uses webpack-dev-server in development
publicPath: 'http://localhost:8080/',
filename: '[name].bundle.js',
// non-entry
chunkFilename: '[name].bundle.js'
};
if (BUILD) {
config.devtool = 'source-map';
} else {
config.devtool = 'eval';
}
/**
* Loaders
*/
config.module = {
noParse: /node_modules\/html2canvas/,
preLoaders: [],
loaders: [
{
// JS LOADER
test: /\.js$/,
loader: 'babel?optional[]=runtime,cacheDirectory',
presets: ['es2015'],
plugins: ['transform-runtime'],
exclude: [/node_modules/,
/cordova_all/
]
},
{
test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/,
loader: 'file?name=[name].[ext]'
//loader: 'url-loader'
}, {
test: /\.html$/,
loader: 'raw'
}]
};
var cssLoader = {
test: /\.css$/,
loader: ExtractTextPlugin.extract('style', 'css?sourceMap!postcss', 'scss', 'sass')
};
config.module.loaders.push(cssLoader);
config.postcss = [
autoprefixer({
browsers: ['last 2 version']
})
];
/**
* Plugins
*/
config.plugins = [
// Extract css files
new ExtractTextPlugin('[name].css')
,
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery"
})
];
// build specific plugins
if (BUILD) {
config.plugins.push(
new webpack.NoErrorsPlugin(),
new webpack.optimize.DedupePlugin(),
// Minify all javascript, switch loaders to minimizing mode
new webpack.optimize.UglifyJsPlugin()
)
}
/**
* Dev server configuration
*/
config.devServer = {
contentBase: './public',
stats: {
modules: false,
cached: false,
colors: true,
chunk: false
}
};
return config;
};
I figured it out. When importing I didn't import the minified version of node modules. I guess webpack's minification and uglification just doesn't cut it.
Thanks for the helpers.