CSS don't work in production using webpack 2 - javascript

I'm workign in a react app using webpack 2 to bundle JS files.
I'm trying to deploy this app in a production enviroment now, but when i deploy the static content in NGinx the CSS doesn't load.
This works fine in dev enviroment. Somone could helpe to solve this problem?
webpack.common.js
/* eslint-disable */
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const webpack = require('webpack');
const path = require('path');
/* eslint-enable */
const ExtractNormalCSS = new ExtractTextPlugin("app.css")
const ExtractCriticalCSS = new ExtractTextPlugin("styles/style_crit.css")
module.exports = () => {
return {
entry: ['./src/main/webapp/app/index'],
node: {
fs: "empty"
},
resolve: {
extensions: [
'.js', '.jsx', '.json'
],
modules: ['node_modules']
},
module: {
rules: [
{
test: /\.json/,
loaders: ['json-loader']
},
{
test: /\.css/i,
exclude: /\.crit.css/,
loaders: ExtractNormalCSS.extract({ fallback: 'style-loader', use: 'css-loader' })
},
{
test: /\.crit.css/i,
loaders: ExtractCriticalCSS.extract({ fallback: 'style-loader', use: 'css-loader' })
},
{
test: /\.scss/i,
exclude: /\.crit.css/,
loaders: ExtractNormalCSS.extract({ fallback: 'style-loader', use: ['css-loader', 'postcss-loader', 'sass-loader'] })
},
{
test: /\.mp4'$/,
loader: 'url-loader?limit=100000'
},
{
test: /\.(jpe?g|png|gif|svg|woff|woff2|ttf|eot)$/i,
loaders: [
'file-loader?hash=sha512&digest=hex&name=[hash].[ext]', {
loader: 'image-webpack-loader',
query: {
gifsicle: {
interlaced: false
},
optipng: {
optimizationLevel: 7
}
}
}
]
}
]
},
plugins: [
new CopyWebpackPlugin([
{
from: './node_modules/swagger-ui/dist',
to: 'swagger-ui/dist'
}, {
from: './src/main/webapp/swagger-ui/',
to: 'swagger-ui'
}, {
from: './src/main/webapp/static/',
to: 'static'
}, {
from: './src/main/webapp/favicon.ico',
to: 'favicon.ico'
}, {
from: './src/main/webapp/robots.txt',
to: 'robots.txt'
}
]),
new HtmlWebpackPlugin({
template: './src/main/webapp/index.html',
chunksSortMode: 'dependency',
inject: 'body'
}),
//new ExtractTextPlugin('styles.css'),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
'window.$': 'jquery'
}),
ExtractNormalCSS,
ExtractCriticalCSS
]
};
};
webpack.prod.js
/* eslint-disable */
const path = require('path');
const webpack = require('webpack');
// const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpackMerge = require('webpack-merge');
const commonConfig = require('./webpack.common.js');
/* eslint-enable */
module.exports = webpackMerge(commonConfig(), {
devtool: 'source-map',
output: {
path: path.resolve('./target/www'),
filename: '[name].js'
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'vendors',
minChunks(module) {
return (module.resource && module.resource.indexOf(path.resolve('node_modules')) === 0);
}
}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
}),
// this conflicts with -p option
new webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false
}
})
],
module: {
rules: [
{
enforce: 'pre',
test: /\.css$/,
loader: 'stripcomment-loader'
},
{
test: /\.js[x]?$/,
loaders: ['react-hot-loader', 'babel-loader?cacheDirectory'],
exclude: /node_modules/,
include: path.resolve('./src/main/webapp/app')
}
]
}
});
webpack.dev.js
/* eslint-disable */
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpackMerge = require('webpack-merge');
const commonConfig = require('./webpack.common.js');
/* eslint-enable */
module.exports = webpackMerge(commonConfig(), {
devtool: 'inline-source-map',
output: {
path: path.resolve('./target/www'),
filename: 'app.js'
},
plugins: [
new webpack.NoEmitOnErrorsPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('development')
}
})
],
module: {
rules: [
{
test: /\.js[x]?$/,
loaders: ['react-hot-loader', 'babel-loader?cacheDirectory'],
exclude: /node_modules/,
include: path.resolve('./src/main/webapp/app')
}
]
},
devServer: {
contentBase: './target/www',
proxy: [
{
context: [
'/api', '/management', '/swagger-resources', '/v2/api-docs', '/h2-console'
],
target: 'http://127.0.0.1:8080/cond21cloud',
secure: false
}, {
context: ['/websocket'],
target: 'ws://l27.0.0.1:8080/cond21cloud',
ws: true
}
]
}
});

Related

Webpack 5 - some styles are missing in production but exist in development

I found that some of the styles are not applied in Production website, but working in development env(localhost).
But Inspecting in Browser Inspector > Sources, I found that in Production sources(css/main.c938xxxxx.css), it missed #roadmap .slick-slide{padding:0 18px}}

Which exist in localhost

Not sure what’s wrong for the production webpack setting. I am using webpack 5
Webpack.base.js
const webpack = require("webpack");
const utils = require("./utils");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const BundleAnalyzerPlugin =
require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
const ProgressBarPlugin = require("progress-bar-webpack-plugin");
const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");
const chalk = require("chalk");
const smp = new SpeedMeasurePlugin();
module.exports = smp.wrap({
entry: "./src/index.jsx",
resolve: {
alias: {
"#": utils.resolve("src"),
},
extensions: ["*", ".js", ".jsx"],
fallback: {…},
},
optimization: {
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
styles: {
name: 'styles',
test: /\.css$/,
chunks: 'all',
enforce: true,
},
},
}
},
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/,
use: [
{
loader: "style-loader",
},
{
loader: "css-loader",
},
{
loader: "sass-loader",
},
{
loader: "sass-resources-loader",
options: {
resources: ["./src/assets/scss/main.scss"],
},
},
],
},
{
test: /\.(png|jpg|gif|svg)$/i,
type: "asset",
parser: {
dataUrlCondition: {
maxSize: 8192
}
}
},
{
test: /\.(ico)$/,
exclude: /node_modules/,
use: ["file-loader?name=[name].[ext]"], // ?name=[name].[ext] is only necessary to preserve the original file name
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: "public/index.html",
filename: "index.html",
favicon: "public/favicon.ico",
manifest: "public/manifest.json",
inject: true,
}),
new webpack.ProvidePlugin({
Buffer: ["buffer", "Buffer"],
}),
new webpack.ProvidePlugin({
process: "process/browser",
}),
new ProgressBarPlugin({
format: ` :msg [:bar] ${chalk.green.bold(":percent")} (:elapsed s)`,
}),
],
});
webpack.dev.js
const { merge } = require("webpack-merge");
const path = require("path");
const base = require("./webpack.base");
const utils = require("./utils");
const Dotenv = require("dotenv-webpack");
module.exports = merge(base, {
mode: "development",
devtool: "inline-source-map",
output: {
publicPath: '/',
assetModuleFilename: (pathData) => {
const filepath = path
.dirname(pathData.filename)
.split("/")
.slice(1)
.join("/");
return `${filepath}/[name].[hash][ext][query]`;
},
},
devServer: {
port: 3300,
static: [
{ directory: utils.resolve("dist") },
{ directory: utils.resolve("public") },
],
},
plugins: [new Dotenv({ path: "./.env.dev })],
});
webpack.uat.js
const { merge } = require("webpack-merge");
const base = require("./webpack.base");
const path = require("path");
const Dotenv = require("dotenv-webpack");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const CompressionPlugin = require("compression-webpack-plugin");
const productionGzipExtensions = ["js", "css"];
module.exports = merge(base, {
mode: "production",
output: {
path: path.join(__dirname, "../dist"),
filename: "js/[name].[contenthash].js",
assetModuleFilename: (pathData) => {
const filepath = path
.dirname(pathData.filename)
.split("/")
.slice(1)
.join("/");
return `${filepath}/[name].[hash][ext][query]`;
},
},
optimization: {
minimizer: [`...`, new CssMinimizerPlugin()],
},
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
},
"sass-loader",
{
loader: "sass-resources-loader",
options: {
resources: ["./src/assets/scss/main.scss"],
},
},
],
},
],
},
plugins: [
new Dotenv({ path: "./.env.uat" }),
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: "css/[name].[contenthash].css",
}),
new CompressionPlugin({
filename: "[path][name].gz[query]",
algorithm: "gzip",
test: new RegExp("\\.(" + productionGzipExtensions.join("|") + ")$"),
threshold: 10240,
minRatio: 0.8,
})
],
});
utils.js
const path = require('path')
module.exports = {
resolve: function(dir) {
return path.join(__dirname, '..', dir)
}
}
Add "style-loader" in webpack.uat.js file.
rules: [
{
test: /\.(sa|sc|c)ss$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: "style-loader",
},
{
loader: "css-loader",
},
"sass-loader",
{
loader: "sass-resources-loader",
options: {
resources: ["./src/assets/scss/main.scss"],
},
},
],
},
],

Webpack unexpected behavior TypeError: Cannot read property 'call' of undefined

Recently we have updated webpack to v4 and soon noticed unexpected errors from webpack during development, which disappears after rebuild of entire bundle.
Our application build using lazy loading and code splitting, which can cause the issue, though I couldn't find anything related to this in the official documentations.
Here the error we get
react_devtools_backend.js:2273 TypeError: Cannot read property 'call' of undefined
our webpack webpack.config.js file.
const webpack = require('webpack');
const path = require('path');
const glob = require('glob');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const AssetsPlugin = require('assets-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
// minification plugins
const TerserJSPlugin = require('terser-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
// image optimization plugins
const ImageminPlugin = require("imagemin-webpack-plugin").default;
const imageminGifsicle = require("imagemin-gifsicle");
const imageminPngquant = require("imagemin-pngquant");
const imageminSvgo = require("imagemin-svgo");
const imageminMozjpeg = require('imagemin-mozjpeg');
const env = require('dotenv').config();
const isProd = process.env.NODE_ENV === 'production';
const isDev = !isProd;
const environment = {
NODE_ENV: process.env.NODE_ENV || 'development',
CONFIG: process.env.CONFIG || 'development',
DEBUG: process.env.DEBUG || false,
};
const plugins = () => {
let plugins = [
new CleanWebpackPlugin(['build', 'cachedImages'], {
root: path.resolve(__dirname, '../dist'),
verbose: true,
dry: false,
}),
new webpack.EnvironmentPlugin(Object.assign(environment, env.parsed)),
new MiniCssExtractPlugin('[chunkhash:5].[name].[hash].css'),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
moment: 'moment',
_: 'lodash',
}),
new webpack.ContextReplacementPlugin(/moment[\\\/]locale$/, /^\.\/(en)$/),
new AssetsPlugin({
filename: 'assets.json',
}),
new ImageminPlugin({
cacheFolder: isDev ? path.resolve(__dirname, '../dist/cachedImages') : null,
externalImages: {
context: 'src',
sources: glob.sync('src/assets/img/**/*.*'),
destination: 'dist/img/',
fileName: (filepath) => {
let name = filepath.split(/img(\/|\\)/).pop();
return name;
},
},
plugins: [
imageminGifsicle({
interlaced: false
}),
imageminMozjpeg({
progressive: true,
arithmetic: false
}),
imageminPngquant({
floyd: 0.5,
speed: 2
}),
imageminSvgo({
plugins: [
{ removeTitle: true },
{ convertPathData: false }
]
}),
],
}),
];
if (isProd) {
plugins.push(
new BundleAnalyzerPlugin({
analyzerMode: 'static',
reportFilename: path.resolve(__dirname, 'analysis.html'),
generateStatsFile: false,
logLevel: 'info',
})
);
}
return plugins;
};
const optimization = () => {
let optimizations = {
concatenateModules: true,
splitChunks: {
cacheGroups: {
vendor: {
name: 'vendor',
test: /[\\/]node_modules[\\/](react|react-dom|lodash|moment)[\\/]/,
chunks: 'all',
},
commons: {
chunks: 'async',
}
}
}
};
if (isProd) {
optimizations.minimizer = [
new TerserJSPlugin({
terserOptions: {
compress: {
pure_funcs: ['console.log'],
drop_console: true,
drop_debugger: true
},
warnings: false
},
parallel: true
}),
new OptimizeCSSAssetsPlugin({})
];
}
return optimizations;
};
const fontLoaders = [
{
test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'url?limit=10000&mimetype=application/font-woff',
}
},
{
test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'url?limit=10000&mimetype=application/font-woff',
}
},
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'url?limit=10000&mimetype=application/octet-stream',
}
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'url?limit=10000&mimetype=image/svg+xml',
}
},
{
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'file',
}
}
];
const config = {
mode: process.env.NODE_ENV,
devtool: isDev ? 'source-map' : '',
context: path.resolve(__dirname, '../src'),
entry: {
bundle: './app.jsx',
embed: './embed.jsx',
styles: './sass_new/main.scss',
vendor: [
'react',
'react-dom',
'redux',
'redux-saga',
'react-redux',
'react-router',
'react-tap-event-plugin',
'lodash',
'moment',
]
},
output: {
publicPath: '/build/',
filename: '[name].[hash].js',
chunkFilename: '[name].[hash].js',
path: path.resolve(__dirname, '../dist/build'),
},
resolve: {
extensions: ['.js', '.jsx', '.json'],
alias: {
config: path.resolve(__dirname, '../config.js'),
utils: path.resolve(__dirname, '../src/utils'),
shared: path.resolve(__dirname, '../src/components/shared'),
services: path.resolve(__dirname, '../src/services'),
store: path.resolve(__dirname, '../src/store'),
constants: path.resolve(__dirname, '../src/constants'),
actions: path.resolve(__dirname, '../src/actions'),
components: path.resolve(__dirname, '../src/components'),
},
},
optimization: optimization(),
plugins: plugins(),
module: {
rules: [
{
test: /\.jsx?$/,
exclude: [/node_modules/, /libs/],
use: {
loader: path.join(__dirname, '../helpers/custom-loader.js'),
options: {
presets: ['#babel/preset-env', '#babel/preset-react'],
plugins: [
'#babel/plugin-proposal-object-rest-spread',
'#babel/plugin-proposal-class-properties',
'#babel/plugin-transform-destructuring',
'#babel/plugin-syntax-dynamic-import',
'#babel/plugin-transform-runtime',
'syntax-async-functions'
]
}
}
},
{
test: /\.scss$/,
use: [
{
loader: MiniCssExtractPlugin.loader
},
'css-loader',
'sass-loader',
]
},
{
test: /\.css$/,
use: [
'css-loader'
]
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loader: "url-loader",
options: {
name: "[path][name].[ext]"
},
},
...fontLoaders
]
},
watchOptions: {
ignored: /node_modules/,
},
};
module.exports = config;
I have no idea how to fix this, and it's taking a lot of time to rebuild entire app after getting this error.

Webpack - devtool: source-map for CSS and eval-source-map for JS?

If I use devtool: 'source-map' it works great with CSS:
But, my JavaScript variable names are no fun:
So, if I use devtool: eval-source-maps. Life is great - debugging JS. But my CSS then points to the big bundle-css instead of the separate files:
How do I have my cake and eat it too?!
I would like to use eval-source-map for JS and source-map for CSS during the same build.
This is my webpack config (using the latest of everything as of this writing):
/* eslint no-console:"off" */
const {resolve} = require('path');
const webpack = require('webpack');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const InlineManifestWebpackPlugin = require('inline-manifest-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const {getIfUtils, removeEmpty} = require('webpack-config-utils');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
// const OfflinePlugin = require('offline-plugin/runtime').install();
module.exports = (env) => {
const {ifProd, ifNotProd} = getIfUtils(env);
const config = {
context: resolve('src'),
entry: './js/index/index.js',
output: {
filename: 'bundle.[name].[hash].js',
path: resolve('dist'),
pathinfo: ifNotProd()
},
// devtool: 'source-map' //This works for CSS but not JS,
devtool: 'eval-source-map' //This works for JS but not css
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /(node_modules)/
},
{
test: /\.js$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {importLoaders: 1, minimize: false, sourceMap: true}
}
]
})
},
{
test: /\.html$/,
use: {
loader: 'html-loader'
}
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader?limit=10000&mimetype=application/font-woff',
query: {
name: 'static/media/files/[name].[hash:8].[ext]'
}
}, {
test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader',
query: {
name: 'static/media/fonts/[name].[hash:8].[ext]'
}
},
{
test: /\.(gif|jpe?g|png)$/,
loader: 'url-loader?limit=25000',
query: {
limit: 10000,
name: 'static/media/images/[name].[hash:8].[ext]'
}
}
]
},
plugins: removeEmpty([
// ifProd(new InlineManifestWebpackPlugin()),
// ifProd(new webpack.optimize.CommonsChunkPlugin({
// names: ['manifest']
// })),
new HtmlWebpackPlugin({
template: './index.html'
// inject: 'head'
}),
// new OfflinePlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: ifProd('"production"', '"development"')
}
}),
new UglifyJSPlugin({
parallel: {
cache: true
},
sourceMap: true
}
),
new OptimizeCssAssetsPlugin({
cssProcessorOptions: {
preset: 'default',
map: {inline: false}
}
}),
new ExtractTextPlugin('styles.[name].[hash].css'),
new BundleAnalyzerPlugin(),
new ProgressBarPlugin(),
])
};
if (env.debug) {
console.log(config);
debugger // eslint-disable-line
}
return config;
};
This seems to work:
{
...webpackConfig,
devtool: false,
plugins: [
new webpack.SourceMapDevToolPlugin({
test: /\.s?[ac]ss$/
}),
new webpack.EvalSourceMapDevToolPlugin({
test: /\.(vue|[jt]sx?)$/
}),
]
}
This will give you inline-source-map for css, scss and sass and eval-source-map for vue, js, jsx, ts and tsx

Webpack 3 Hot Reload Very Slow

Info: I am using webpack 3.4.1 with webpack-dev-server 2.5.1
Using the below configuration with '--hot --inline', I get a very slow hot reload. I can remove '--hot' and have very fast reload, but I would prefer to change css on the fly, using hot reload.
common.js
const webpack = require('webpack');
const htmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const { resolvePath } = require('./helpers');
const env = process.env.NODE_ENV;
const cssLoader = {
test: /\.css$/,
loader: ExtractTextPlugin.extract('css-loader?sourceMap')
};
const lessLoader = {
test: /\.less$/,
loaders: ['style-loader', 'css-loader', 'less-loader']
}
const babelLoader = {
test: /\.js?$/,
include: [
resolvePath('src/app'),
],
exclude: /(node_modules)/,
loader: 'babel-loader',
};
const htmlLoader = {
test: /\.html$/,
loader: 'ngtemplate-loader?relativeTo=' + resolvePath('src') + '/!html-loader'
};
const fontLoader = {
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader?limit=10000&mimetype=application/font-woff'
};
const fileLoader = {
test: /\.(ttf|eot|svg|otf|png|jpg|gif|ico)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader'
};
const jsonLoader = {
test: /\.json$/,
loader: 'json-loader'
};
const tinyMCELoader = {
test: require.resolve('tinymce/tinymce'),
loaders: [
'imports-loader?this=>window',
'exports-loader?window.tinymce'
]
}
const tinyMCEThemeLoader = {
test: /tinymce\/(themes|plugins)\//,
loader: 'imports-loader?this=>window'
}
const config = {
devtool: 'inline-source-map',
entry: {
vendor: resolvePath('src/app/vendor.js'),
app: resolvePath('src/app/app.js')
},
target: 'web',
output: {
path: resolvePath('public'),
publicPath: '/',
filename: '[name].js'
},
module: {
loaders: [
babelLoader,
lessLoader,
htmlLoader,
cssLoader,
fontLoader,
fileLoader,
jsonLoader,
tinyMCELoader,
tinyMCEThemeLoader
]
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor'
}),
new ExtractTextPlugin('[name].[contenthash].css'),
new htmlWebpackPlugin({
template: resolvePath('public/index.ejs'),
favicon: resolvePath('src/favicon.ico'),
inject: true,
env
})
],
resolve: {
alias: {
api: resolvePath('src/app/api/apiUrl.js')
}
}
};
module.exports = config;
and dev.js
const webpackMerge = require('webpack-merge');
const commonConfig = require('./common.js');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const { resolvePath } = require('./helpers');
const { HOST, PORT } = process.env;
const port = PORT || 1337;
const host = HOST || 'localhost';
const devConfig = {
devtool: 'cheap-module-source-map',
devServer: {
contentBase: resolvePath('public'),
port,
host,
historyApiFallback: true,
watchOptions: {
aggregateTimeout: 300,
poll: 1000
}
},
plugins: [
new UglifyJsPlugin({
include: ['vendor.js']
})
]
};
module.exports = () => webpackMerge(commonConfig, devConfig);
I tried removing the Extract-Text-Plugin, but to no avail. Any ideas on to
make hot reload fast? I was thinking of disableing the compiling of vendor.js, but I don't know here to add that. Thanks.

CSS_MODULES: Module build failed with extract-text-webpack-plugin

When I extract CSS with CSS modules in production environment, it reports an error, but it goes well in development environment.
webpack.base.js
const path = require("path")
const webpack = require("webpack")
module.exports = function(env) {
return {
entry: {
main: path.resolve(__dirname, "../src/main.js"),
},
output: {
path: path.resolve(__dirname, "../dist"),
sourceMapFilename: "[name].map",
publicPath: "/",
filename: (env === "dev") ? "[name].js" : "[name].[hash:16].js",
},
resolve: {
extensions: [".ts", ".js", ".json"],
modules: [path.join(__dirname, "../src"), "node_modules"]
},
module: {
loaders: [{
test: /\.jsx?$/,
use: ["babel-loader"],
exclude: "/node_modules/"
},
{
test: /\.(png|jpg|gif)$/,
use: ["url-loader?limit=20000&name=images/[hash:16].[ext]"],
exclude: "/node_module/"
},
{
test: /\.scss$/,
use: ["style-loader", "css-loader?modules", "postcss-loader", "sass-loader"],
exclude: ["/node_module/", path.resolve(__dirname, "../static")]
},
{
test: /\.scss$/,
use: ["style-loader", "css-loader", "sass-loader"],
include: path.resolve(__dirname, "../static")
},
],
},
}
}
webpack.prod.js
const path = require("path");
const webpack = require("webpack");
const webpackMerge = require("webpack-merge");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const HTMLWebpackPlugin = require("html-webpack-plugin");
const autoprefixer = require("autoprefixer");
const precss = require("precss");
const baseConfig = require("./webpack.base.js");
const config = require("./config.js");
const vendor = config.vendor;
module.exports = function(env) {
return webpackMerge(baseConfig(env), {
entry: {
main: path.resolve(__dirname, "../src/main.js"),
vendor,
},
module: {
loaders: [{
test: /\.scss$/,
loaders: ExtractTextPlugin.extract({
fallbackLoader: "style-loader",
use: [
"css-loader?minimize&modules&importLoaders=1&localIdentName=[name]_[local]_[hash:base64:5]",
"postcss-loader",
"sass-loader"
]
}),
exclude: ["/node_module/", path.resolve(__dirname, "../static")]
},
{
test: /\.scss$/,
loaders: ExtractTextPlugin.extract({
fallbackLoader: "style-loader",
use: [
"css-loader?minimize",
"sass-loader"
]
}),
include: path.resolve(__dirname, "../static")
},
],
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
screw_ie8: true,
conditionals: true,
unused: true,
comparisons: true,
sequences: true,
dead_code: true,
evaluate: true,
if_return: true,
join_vars: true,
},
output: {
comments: false,
},
}),
new ExtractTextPlugin({
filename: "style.[contenthash:16].css",
disable: false,
allChunks: true,
}),
new HTMLWebpackPlugin({
template: "src/index.html"
}),
new webpack.optimize.CommonsChunkPlugin({
name: ["vendor", "manifest"]
}),
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production")
}
}),
new webpack.LoaderOptionsPlugin({
options: {
postcss() {
return [precss, autoprefixer];
}
}
})
]
})
}
webpack.dev.js
const path = require("path");
const webpack = require("webpack")
const webpackMerge = require("webpack-merge");
const OpenBrowserPlugin = require("open-browser-webpack-plugin");
const autoprefixer = require("autoprefixer");
const precss = require("precss");
const baseConfig = require("./webpack.base.js");
const config = require("./config");
const port = config.port;
module.exports = function(env){
console.log(`
#################################################
Server is listening at: http://localhost:${config.port}
#################################################
`);
return webpackMerge(baseConfig(env),{
entry:[
"react-hot-loader/patch",
"webpack-dev-server/client?http://localhost:" + port,
"webpack/hot/only-dev-server",
path.resolve(__dirname,"../src/main.js"),
],
devtool: "cheap-module-source-map",
plugins:[
new webpack.HotModuleReplacementPlugin(),
new OpenBrowserPlugin({ url: "http://localhost:" + port }),
new webpack.LoaderOptionsPlugin({
options:{
postcss(){
return[precss, autoprefixer];
}
}
})
],
devServer:{
hot:true,
port:config.port,
historyApiFallback:true,
}
})
}
Error message in console
ERROR in ./~/css-loader?modules!./~/postcss-loader!./~/sass-loader/lib/loader.js!./~/extract-text-webpack-plugin/loader.js?{"omit":1,"remove":true}!./~/style-loader!./~/css-loader?minimize&modules&importLoaders=1&localIdentName=[name]_[local]_[hash:base64:5]!./~/postcss-loader!./~/sass-loader/lib/loader.js!./src/components/Welcome/style.scss
Module build failed:
display: flex;
^
Invalid CSS after "module.exports": expected "{", was '= {"box":"style_box'
in C:\Users\Charley\Desktop\myproj\gogogo\src\components\Welcome\style.scss (line 2, column 16)
# ./src/components/Welcome/style.scss 4:14-512
# ./src/components/Welcome/index.js
# ./src/router/components.js
# ./src/router/index.js
# ./src/main.js
What's the matter with my code and how can I fix it? I think the problem is extract-text-webpack-plugin, but I don't know what goes wrong here.
I changed my webpack.prod.js
const path = require("path");
const webpack = require("webpack");
const webpackMerge = require("webpack-merge");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const HTMLWebpackPlugin = require("html-webpack-plugin");
const autoprefixer = require("autoprefixer");
const precss = require("precss");
const baseConfig = require("./webpack.base.js");
const config = require("./config.js");
const vendor = config.vendor;
module.exports = function(env){
return webpackMerge(baseConfig(env),{
entry:{
main:path.resolve(__dirname,"../src/main.js"),
vendor,
},
module:{
// modified goes here
rules:[
{
test:/\.jsx?$/,
use:["babel-loader"],
exclude:"/node_modules/"
},
{
test: /\.(png|jpg|gif)$/,
use: ["url-loader?limit=20000&name=images/[hash:16].[ext]"],
exclude: "/node_module/"
},
{
test: /\.s?css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: [
"css-loader?minimize&modules&importLoaders=1&localIdentName=[name]_[local]_[hash:base64:5]",
"sass-loader",
"postcss-loader"
]
}),
exclude: ["/node_module/",path.resolve(__dirname,"../static")]
},
{
test: /\.s?css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: [
"css-loader?minimize",
"sass-loader",
"postcss-loader"
]
}),
include: [path.resolve(__dirname,"../static")]
}
],
},
plugins:[
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
screw_ie8: true,
conditionals: true,
unused: true,
comparisons: true,
sequences: true,
dead_code: true,
evaluate: true,
if_return: true,
join_vars: true,
},
output: {
comments: false,
},
}),
new ExtractTextPlugin({
filename:"style.[contenthash:16].css",
disable:false,
allChunks:true,
}),
new HTMLWebpackPlugin({
template:"src/index.html"
}),
new webpack.optimize.CommonsChunkPlugin({
name: ["vendor","manifest"]
}),
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production")
}
}),
new webpack.LoaderOptionsPlugin({
options:{
postcss(){
return[precss, autoprefixer];
},
sassLoader: {
sourceMap: true
},
}
})
]
})
}

Categories

Resources