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
},
}
})
]
})
}
Related
I would be grateful for any help or advice. I have compiled the configuration of the webpack, everything works in production mode, but the webpack-dev-server does not see static files and gives the error "Cannot get /". How can I solve this problem? Thank you in advance for the answer. Here is my webpack.config.js
const path = require("path");
const { VueLoaderPlugin } = require("vue-loader");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const HTMLWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerWebpackPlugin = require("css-minimizer-webpack-plugin");
const TerserWebpackPlugin = require("terser-webpack-plugin");
// const autoprefixer = require("autoprefixer");
const isProd = process.env.NODE_ENV === "production";
const isDev = !isProd;
const optimization = () => {
const config = {
runtimeChunk: "single",
splitChunks: {
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: "vendors",
priority: -10,
chunks: "all",
},
},
},
};
if (isProd) {
config.minimizer = [
new CssMinimizerWebpackPlugin(),
new TerserWebpackPlugin(),
];
}
return config;
};
module.exports = {
entry: path.resolve(__dirname, "src", "index.js"),
mode: isProd ? "production" : "development",
output: {
path: path.join(__dirname, "build"),
filename: "[name].[contenthash:8].js",
chunkFilename: "[name].[contenthash:8].js",
publicPath: "./",
},
devtool: isDev ? "source-map" : false,
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
},
{
test: /\.vue$/,
loader: "vue-loader",
},
{
test: /\.(eot|ttf|woff|woff2)(\?\S*)?$/,
loader: "file-loader",
options: {
name: "[name][contenthash:8].[ext]",
},
},
{
test: /\.(png|jpe?g|gif|webm|mp4|svg)$/,
loader: "file-loader",
options: {
name: "[name][contenthash:8].[ext]",
outputPath: "assets/img",
esModule: false,
},
},
{
test: /\.s?css$/,
use: [
"style-loader",
{
loader: MiniCssExtractPlugin.loader,
options: {
esModule: false,
},
},
"css-loader",
],
},
],
},
plugins: [
new VueLoaderPlugin(),
new MiniCssExtractPlugin({
filename: "[name].[contenthash:8].css",
chunkFilename: "[name].[contenthash:8].css",
}),
new HTMLWebpackPlugin({
template: path.join(__dirname, "src", "public", "index.html"),
filename: "start-page.html",
alwaysWriteToDisk: true,
minify: {
collapseWhitespace: isProd,
},
}),
new CleanWebpackPlugin(),
],
resolve: {
alias: {
vue: "#vue/runtime-dom",
},
extensions: ["*", ".js", ".vue", ".json"],
},
optimization: optimization(),
devServer: {
compress: true,
port: 9000,
hot: true,
client: {
overlay: true,
},
},
};
Here is a project folders
According to the doc, you need to set the publicPath in the devServer.
Look at the documentation
module.exports = {
//...
devServer: {
static: {
directory: path.join(__dirname, 'public'),
},
compress: true,
port: 9000,
},
};
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"],
},
},
],
},
],
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.
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
}
]
}
});
With this config I get an app.bundle.js, app.map, app.css. The problem is that app.map contains only the css related code. If I don't use ExtractTextPlugin then the sourcemap contains all the css and js related code but I have to keep css in a separate file. If I don't get map for css that's fine but for js it is a must have.
// webpack.common.config
var webpack = require('webpack');
var helpers = require('./helpers');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var webpackPostcssTools = require('webpack-postcss-tools');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var autoprefixer = require('autoprefixer');
var postcssImport = require('postcss-import');
var map = webpackPostcssTools.makeVarMap('src/css/index.css');
var ngAnnotatePlugin = require('ng-annotate-webpack-plugin');
const METADATA = {
baseUrl: '/'
};
module.exports = {
metadata: METADATA,
entry: {
'app': './src/js/app.js',
'vendor': './src/vendor.js'
},
resolve: {
extensions: ['', '.js'],
root: helpers.root('src'),
modulesDirectories: ['node_modules']
},
module: {
preLoaders: [
{ test: /\.js$/, loaders:['eslint', 'source-map-loader'], exclude: /node_modules/ }
],
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.json$/,
loader: 'json-loader'
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract('style-loader', 'css?sourceMap&importLoaders=1!postcss-loader?sourceMap')
},
{
test: /\.html$/,
loader: 'raw-loader',
exclude: [helpers.root('src/index.html')]
},
{
test: /\.woff(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "url-loader?limit=10000&minetype=application/font-woff"
}, {
test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "file-loader"
}
]
},
plugins: [
new ngAnnotatePlugin({
add: true,
}),
new ExtractTextPlugin("[name].css", { allChunks: true }),
new webpack.optimize.OccurenceOrderPlugin(true),
new webpack.optimize.CommonsChunkPlugin({
name: helpers.reverse(['vendor', 'app']),
minChunks: Infinity
}),
new CopyWebpackPlugin([{
from: 'src/res',
to: 'res'
}, {
from: 'src/templates',
to: 'templates'
}
}
]),
new HtmlWebpackPlugin({
template: 'src/index.html',
chunksSortMode: 'none'
}),
],
postcss: function (webpack) {
return [
//webpackPostcssTools.prependTildesToImports,
postcssImport({ addDependencyTo: webpack }),
require('postcss-custom-properties')({
variables: map.vars
}),
require('postcss-custom-media')({
extensions: map.media
}),
require('postcss-calc'),
autoprefixer
];
},
node: {
global: 'window',
crypto: 'empty',
module: false,
clearImmediate: false,
setImmediate: false
},
};
// webpack.dev.config
var helpers = require('./helpers');
var webpackMerge = require('webpack-merge');
var commonConfig = require('./webpack.common.js');
var DefinePlugin = require('webpack/lib/DefinePlugin');
const ENV = process.env.ENV = process.env.NODE_ENV = 'development';
const METADATA = webpackMerge(commonConfig.metadata, {
host: 'localhost',
port: 8000,
ENV: ENV
});
module.exports = webpackMerge(commonConfig, {
debug: true,
metadata: METADATA,
devtool: 'source-map',
output: {
path: helpers.root('www'),
filename: '[name].bundle.js',
sourceMapFilename: '[name].map',
chunkFilename: '[id].chunk.js'
},
plugins: [
new DefinePlugin({
'ENV': JSON.stringify(METADATA.ENV)
}),
],
devServer: {
port: METADATA.port,
host: METADATA.host,
historyApiFallback: true,
watchOptions: {
aggregateTimeout: 300,
poll: 1000
}
},
eslint: {
configFile: './.eslintrc.js',
emitError: false,
emitWarning: false,
fix: true
},
node: {
global: 'window',
crypto: 'empty',
process: true,
module: false,
clearImmediate: false,
setImmediate: false
}
});
The issue seems to be that ExtractTextPlugin overwrites other sourcemaps, according to this discussion: https://github.com/webpack/extract-text-webpack-plugin/issues/119
You can fix this issue by ensuring that each output file that gets a sourcemap gets a different filename, like this:
sourceMapFilename: '[file].map'