webpack dev server does not show the content - javascript

I have the following problem when running the webpack dev server:
when I run npm start, it show the following:
➜ directory git:(staging) ✗ npm start
directory #1.0.0 start directory
BUILD_DEV=1 BUILD_STAGING=1 ./node_modules/webpack-dev-server/bin/webpack-dev-server.js
http://localhost:8080/
webpack result is served from /undefined/
content is served from
directory
404s will fallback to /index.html
Hash: 75773622412153d5f921
Version: webpack 1.12.11
Time: 43330ms
I guess the problem might because the following line:
webpack result is served from /undefined/
When I open the browser at http://localhost:8080/, it appear as follow:
Cannot GET /
and there is no thing in the console.
Do you have any ideas for this problem ?
UPDATE: WEBPACK CONFIG FILE
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const merge = require('webpack-merge');
const nodeModulesDir = path.resolve(__dirname, 'node_modules');
const deps = [
'moment/min/moment.min.js',
'underscore/underscore-min.js',
];
/* Include SASS path here if you want to this in your sass files:
* #import 'bourbon';
*/
const bourbon = require('node-bourbon').includePaths;
const TARGET = process.env.npm_lifecycle_event;
const ROOT_PATH = path.resolve(__dirname);
const SASS_DEPS = [bourbon].toString();
const BUILD_NUMBER = process.env.CI_BUILD_NUMBER;
const common = {
entry: path.resolve(ROOT_PATH, 'app/index.js'),
output: {
filename: BUILD_NUMBER + '-[hash].js',
path: path.resolve(ROOT_PATH, 'build'),
publicPath: `/${BUILD_NUMBER}/`,
},
module: {
loaders: [
{
test: /\.scss$/,
loaders: ['style', 'css', 'sass?includePaths[]=' + SASS_DEPS],
include: path.resolve(ROOT_PATH, 'app'),
},
{
test: /\.css$/,
loaders: [
'style',
'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
'sass?includePaths[]=' + SASS_DEPS,
'postcss'
],
include: path.resolve(ROOT_PATH),
exclude: /(pure\/grids|Grids).*\.css$/,
},
{
test: /(pure\/grids|Grids).*\.css$/,
loaders: [
'style',
'css',
'sass?includePaths[]=' + SASS_DEPS,
],
include: path.resolve(ROOT_PATH),
},
{
test: /\.woff(2)?(\?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',
},
{
test: /\.json$/,
loader: 'json',
},
],
},
plugins: [
new HtmlWebpackPlugin({
title: 'My App',
template: path.resolve(ROOT_PATH, 'app/index.html'),
inject: 'body',
minify: {
removeComments: true,
collapseWhitespace: true,
},
}),
new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(process.env.BUILD_DEV || 'false')),
__STAGING__: JSON.stringify(JSON.parse(process.env.BUILD_STAGING || 'false')),
__API_HOST__: JSON.stringify(process.env.BUILD_STAGING ? 'my.api' : 'my.api'),
}),
],
resolve: {
alias: {
'styles': path.resolve(ROOT_PATH, 'app/styles'),
},
extensions: ['', '.js', '.jsx', '.json'],
},
postcss: function() {
return [
require('postcss-import'),
require('autoprefixer'),
require('postcss-cssnext'),
]
}
};
if (TARGET === 'start' || !TARGET) {
module.exports = merge(common, {
output: {
filename: '[hash].js',
path: path.resolve(ROOT_PATH, 'build'),
publicPath: '/',
},
devtool: 'eval-source-map',
module: {
loaders: [
{
test: /\.jsx?$/,
loaders: [
'react-hot',
'babel-loader'
],
include: path.resolve(ROOT_PATH, 'app'),
},
],
},
devServer: {
colors: true,
historyApiFallback: true,
hot: true,
inline: true,
progress: true,
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
});
} else if (TARGET === 'build' || TARGET === 'builds') {
const config = {
resolve: {
alias: {},
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
include: path.resolve(ROOT_PATH, 'app'),
},
],
noParse: [],
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
minimize: true,
compressor: {
screw_ie8: true,
warnings: false,
},
compress: {
warnings: false,
},
output: {
comments: false,
},
}),
new webpack.optimize.DedupePlugin(),
new webpack.DefinePlugin({
'process.env': { 'NODE_ENV': JSON.stringify(process.env.NODE_ENV) },
}),
],
};
deps.forEach((dep) => {
const depPath = path.resolve(nodeModulesDir, dep);
config.resolve.alias[dep.split(path.sep)[0]] = depPath;
config.module.noParse.push(depPath);
});
module.exports = merge(common, config);
}

Same problem occurred to me when i started using babel-loader > 6.
It was fixed by adding contentBase in webpack dev server configuration.
In my case it looked like this
new WebPackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true,
contentBase: __dirname + '/public'
}).listen(3000, 'localhost')

I would be great to see your webpack config file to pin point the exact problem, but from the error message, there could be multiple problem
Make sure you are on the right port
Make sure your webpack config has
path and public path setup
Make sure you have contentBase setup as
well
Without seeing your webpack file and more concrete detail, it is quite hard to pinpoint the issue. But you can always go to https://webpack.github.io/docs/webpack-dev-server.html for information on how to set it up.

Related

Webpack 5 not showing images

I have a vue 3 app where I set up webpack 5 eventually. As I see I eliminated all my issues now the only thing remains is that it does not load my svg-s and images when I run the webpack serve script in dev mode. How can I configure webpack so that it would bundle my svg-s from the scr/assets folder?
my webpack config:
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const { VueLoaderPlugin } = require('vue-loader');
const env = process.env.NODE_ENV || 'development';
const mode = process.env.VUE_APP_MODE || 'not-fullstack';
module.exports = {
mode: 'development',
entry: './src/main.js',
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'dist'),
},
resolve: {
alias: {
vue: '#vue/runtime-dom',
'#': path.join(__dirname, 'src'),
},
fallback: { crypto: false, stream: false },
},
module: {
rules: [
{
test: /\.vue$/,
use: [
{
loader: 'vue-loader',
},
],
},
{
test: /\.css$/i,
use: ['style-loader', 'css-loader', 'postcss-loader'],
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: 'images/[name].[hash].[ext]',
},
type: 'asset/resource',
},
{
test: /\.svg$/i,
use: [
{
loader: 'url-loader',
options: {
encoding: false,
},
},
],
},
],
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: path.resolve(__dirname, './public/index.html'),
}),
new VueLoaderPlugin(),
new CopyPlugin([
{ noErrorOnMissing: true, from: './src/assets', to: 'images' },
]),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(env),
'process.env.VUE_APP_MODE': JSON.stringify(mode),
}),
],
devServer: {
historyApiFallback: true,
compress: true,
port: 3000,
},
};
And I reference my svg-s in my Vue component like this:
<img src="../../assets/logo.svg" alt="logo" />
As you can see I tried with the copy-webpack-plugin, maybe I just configured it wrong.
Thank you for your help in advance!
The config in webpack5 changed a lot
{
loader: 'url-loader',
options: {
encoding: false,
},
This is not working anymore. The url-loader is even removed from the npm packages.
The current way is found in the documentation
https://webpack.js.org/guides/asset-management/#loading-images

Webpack unable to resolve the dependencies

I have the following folder structure (here is the demo app source code):
MyComp.scss:(app\web\src\components\MyComp\MyComp.scss)
I've below URL:
.content{
background-image: url(/icons/myIcon.png); // should resolve to web\icons\myIcon.png
}
Webpack is throwing error for this:
Error: Can't resolve '/icons/myIcon.png' in
'C:\app\web\src\components\
MyContainer.jsx: (app\web\src\containers\MyContainer\MyContainer.jsx) I am using below absolute imports which are giving errors:
import MyComp from 'components/MyComp'; // This should resolve to app\web\src\components\MyComp\MyComp.jsx
import { authorizingUser } from 'myRedux'; // should resolve to app\unify\myRedux\modules\auth\actions.js
Moreover, node_modules imports are also failing:
ERROR in ./node_modules/node-fetch/index.js 10:11-26 Module not found:
Error: Can't resolve 'http' in 'C:\node_modules\node-fetch'
Here is how my webpack config is:
config.js: (app\web\build\config.js)
const path = require('path');
const root = path.resolve(__dirname, '..', '..', '..'); // Project root.
const webRoot = path.resolve(root, 'app', 'web');
const assetPath = path.resolve(root, 'web', 'dist');
module.exports = { root, webRoot, assetPath };
webpack.frontend.config: (app\web\build\webpack.frontend.config.js)
require('dotenv').config();
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const AssetsPlugin = require('assets-webpack-plugin');
const config = require('./config.js');
const PROD = process.env.NODE_ENV === 'production';
const cssLoader = (enableModules = true) => {
return {
loader: 'css-loader',
options: {
modules: enableModules,
sourceMap: !PROD,
importLoaders: 2,
modules: {
localIdentName: PROD ? '[local]__[hash:base64:5]' : '[local]',
},
},
};
};
const postCssLoader = {
loader: 'postcss-loader',
options: {
sourceMap: !PROD,
postcssOptions: {
public: [
'postcss-preset-env',
{
// Options
browsers: 'last 2 versions',
},
],
},
},
};
const sassLoader = {
loader: 'sass-loader',
options: {
sourceMap: !PROD,
},
};
const localStyleLoaders = [cssLoader(), postCssLoader, sassLoader];
// We want to disable css module.
const globalStyleLoaders = [cssLoader(false), postCssLoader, sassLoader];
const devPlugins = [new webpack.HotModuleReplacementPlugin()]; // <- To generate hot update chunk
const prodPlugins = [];
const devEntries = [
`webpack-dev-server/client?path=https://my-domain.com:443`, // <-- Enables web socket connection (needs url & port)
'webpack/hot/dev-server', // <- To perform HMR in the browser
];
const clientAppEntryFilePath = path.resolve(config.webRoot, 'src/client.jsx');
module.exports = {
entry: {
frontEndMain: [
'babel-polyfill',
...(PROD ? [] : devEntries),
clientAppEntryFilePath,
],
},
output: {
path: config.assetPath,
filename: '[name]-[hash].js', // Hash is used to force cache invalidation.
publicPath: PROD
? '/dist'
: `https://my-domain.com:443/dist/`,
},
module: {
rules: [
//JavaScript & JSX
{
test: /\.(jsx|js)$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
// For local styles.
{
test: /\.(scss|css)$/,
use: PROD
? [MiniCssExtractPlugin.loader, ...localStyleLoaders]
: ['style-loader', ...localStyleLoaders],
include: path.resolve(config.webRoot, 'src'),
exclude: path.resolve(config.webRoot, 'src', 'theme'),
},
// Global styles
// Just like the normal style loader stack, but without css modules so we don't modify
// classnames for our style libraries like bootstrap, slick, etc
{
test: /\.(scss|css)$/,
use: PROD
? [MiniCssExtractPlugin.loader, ...globalStyleLoaders]
: ['style-loader', ...globalStyleLoaders],
include: [path.resolve(config.webRoot, 'src', 'theme'), /node_modules/],
},
// Images: Copy image files to build folder
{
test: /\.(?:ico|gif|png|jpg|jpeg)$/i,
loader: 'url-loader',
options: {
limit: 10240,
},
},
{
test: /\.woff2?(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'application/font-woff',
},
},
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'application/octet-stream',
},
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'mimetype=image/svg+xml',
},
},
{
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: 'file-loader',
},
],
},
resolve: {
modules: [
'node_modules',
// Since I am using absolute import for custom modules/js. So this is required.
'app',
'app/unify',
'app/web/src',
],
extensions: ['.js', '.jsx'],
},
plugins: [
...(PROD ? prodPlugins : devPlugins),
new CleanWebpackPlugin(),
// Since I have hashed frontEnd js/css, so this generates assets info file on root and
// which has assets info.
new AssetsPlugin({
path: config.root,
filename: 'web-frontend-assets.json',
prettyPrint: true,
}),
new webpack.DefinePlugin({
// To resolve this error on production build.
// "You are currently using minified code outside of NODE_ENV === 'production'"
'process.env': {
NODE_ENV: JSON.stringify(PROD ? 'production' : 'development'),
PLATFORM: JSON.stringify(process.env.PLATFORM),
WEB_ENV: JSON.stringify(process.env.WEB_ENV),
},
__CLIENT__: true,
__SERVER__: false,
__DEVELOPMENT__: process.env.NODE_ENV !== 'production',
}),
],
devServer: {
https: {
key: fs.readFileSync(`${config.webRoot}/certs/key.pem`),
cert: fs.readFileSync(`${config.webRoot}/certs/cert.pem`),
},
host: 'my-domain.com',
port: '443',
quiet: true,
inline: true,
hot: true,
compress: true, // <- Enables HMR in webpack-dev-server and in libs running in the browser
historyApiFallback: true,
disableHostCheck: true,
clientLogLevel: 'silent',
publicPath: `https://my-domain.com:443/dist/`,
contentBase: `https://my-domain.com:443`,
headers: { 'Access-Control-Allow-Origin': '*' },
stats: { colors: true },
},
node: false,
stats: {
preset: 'detailed',
assets: true,
builtAt: true,
moduleAssets: false,
assetsSpace: 15,
modulesSpace: 15,
colors: true,
env: true,
errors: true,
errorDetails: true,
errorStack: true,
reasons: true,
modules: true,
},
};
package.json:
"scripts": {
"start-frontend": "webpack --config ./app/web/build/webpack.frontend.config.js"
},
I am not sure, what exactly I need to pass in entry.frontEndMain, output.publicPath, devServer.publicPath, devServer.contentBase

copy-webpack-plugin doesn't copy files

I try to just copy files to check simple webpack config. So I stuck trying to make copy-webpack-plugin to work - nothing happens: no copied files, no errors, nothing
Common config (webpack.common.js):
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const postCssPlugin = [
require('postcss-import'),
require('postcss-nested'),
require('postcss-simple-vars'),
require('autoprefixer')({
browsers: [
'last 3 versions',
'android 4.2'
]
})
];
module.exports = {
context: path.resolve(__dirname, '../src'),
entry: [
'babel-polyfill',
path.resolve(__dirname, '../src/index.js')
],
output: {
path: path.resolve(__dirname, '../dist/js'),
publicPath: '',
filename: 'app.js'
},
resolve: {
extensions: ['.jsx', '.js', '.json']
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.p?css$/,
use: [
'style-loader',
'css-loader',
{
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: postCssPlugin
}
}
]
}
]
},
plugins: [
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../src/assets/**/*'),
to: path.resolve(__dirname, '../dist/assets'),
flatten: true
}
])
],
stats: {
modules: true,
warnings: false,
version: true,
timings: true,
performance: false,
hash: true,
errors: true,
errorDetails: true,
colors: true,
builtAt: true
}
};
webpack.prod.js:
const commonWebpackConfig = require('./webpack.common.js');
const UglifyJsWebpackPlugin = require('uglifyjs-webpack-plugin');
module.exports = Object.assign(commonWebpackConfig, {
mode: 'production',
plugins: [
new UglifyJsWebpackPlugin({
sourceMap: true
})
]
});
And build starting file build.js:
const webpack = require('webpack');
const webpackProdConfig = require('./webpack.config/webpack.prod.js');
webpack(webpackProdConfig, (err, stats) => {
if (err || stats.hasErrors()) {
console.error(err.stack || err);
}
console.log('Successfully compiled!');
});
So could anyone figure out why doesn't it work and where am I wrong?
copy-webpack-plugin: 4.5.2
node: 9.1.0
npm: 6.3.0
windows: 10
Addition - folder structure:
Try to copy from the dist folder. For me it worked
es.
new CopywebpackPlugin([{
from: path.resolve(__dirname, 'node_modules/mettrr-component-library/dist/img'),
to: path.resolve(__dirname, 'src/assets/img')
}]),

webpack is compile time is very slow

My webpack is going very slow when it starts and when theres a change - compiling. Actually making development very slow right now. I'm only using greensock as the vendor but nothing else. I'm using only a few images too.. not sure.
Here is the code:
const path = require('path');
var webpack = require('webpack');
var htmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
// const ASSET_PATH = process.env.ASSET_PATH || '/'; ,
//publicPath: '/dist'
var isProd = process.env.NODE_ENV === 'production';
var cssDev = ['style-loader', 'css-loader', 'sass-loader'];
const VENDOR_LIBS =['gsap'];
var cssProd = ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
'css-loader', 'sass-loader'
],
publicPath: '/dist'
});
var cssConfig = isProd ? cssProd : cssDev;
module.exports = {
entry: {
index: './src/js/index.js',
vendor: VENDOR_LIBS
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[hash].js'
},
devServer: {
//contentBase: path.join(__dirname, "/dist"),
compress: true,
port: 3000,
hot: true,
stats: "errors-only",
open: true
},
optimization: {
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendor',
chunks: 'all'
}
}
}
},
module:{
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader'
},
{
test: /\.css$/,
use:[
"style-loader" , "css-loader"
]
},
{
test: /\.scss$/,
use: cssConfig
},
{
test: /\.pug$/,
use: ['html-loader', 'pug-html-loader']
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
use: ['file-loader?name=[name].[ext]&outputPath=images/&publicPath=images/',
'image-webpack-loader'
]
},
{
test: /\.(eot|ttf|woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
use: 'file-loader?name=[name].[ext]&outputPath=fonts/&publicPath=fonts/'
}
]
},
plugins: [
new htmlWebpackPlugin({
title: '',
template: './src/index.html',
minify: {
collapseWhitespace: true
},
hash: true,
inject: true
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
new ExtractTextPlugin({
filename: 'app.css',
disable: !isProd,
allChunks: true
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
})
]
};
Here is the package.json scripts:
"scripts": {
"killallProcesses": "killall node && webpack-dev-server",
"start": "webpack-dev-server",
"dev": "webpack -d",
"prod": "npm run clean && NODE_ENV=production webpack -p",
"clean": "rimraf ./dist/* ",
"deploy-gh": "npm run prod && git subtree push --prefix dist origin gh-pages"
}
So, not sure what is wrong here but compile time is very slow - using greensock as vendor but nothing else.. So not sure why its so slow. Even when I start webpack its brutal slow.
Webpack version 4 came with a huge speed imporvements.
First, use this strategy to split your config files for production and for development. Just follow the idea, don't follow the configurations because some of them are outdated.
Your config is the new config schema, based on webpack 4, só i'm going to do some tweaks to the basic one, and you can split them using the strategy i've linked.
First: install mini-css-extract-plugin.
const path = require('path');
const webpack = require('webpack');
const htmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const isProd = process.env.NODE_ENV === 'production';
const cssDev = ['style-loader', 'css-loader', 'sass-loader'];
const cssProd = [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'];
const cssConfig = isProd ? cssProd : cssDev;
// content hash is better for production which helps increasing cache.
// contenthash is the hash generated given the content of the file, so this is going to change only if the content changed.
const outputFilename = isProd ? '[name].[contenthash].js' : 'name.[hash].js';
module.exports = {
entry: './src/js/index.js',
output: {
// dist folder is by default the output folder
filename: outputFilename
},
// this should go into the webpack.dev.js
devServer: {
//contentBase: path.join(__dirname, "/dist"),
compress: true,
port: 3000,
hot: true,
stats: "errors-only",
open: true
},
optimization: {
splitChunks: {
cacheGroups: {
commons: {
// this takes care of all the vendors in your files
// no need to add as an entrypoint.
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all'
}
}
}
},
module:{
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader'
},
{
test: /\.css$/,
use:[MiniCssExtractPlugin.loader, 'css-loader']
},
{
test: /\.scss$/,
use: cssConfig
},
{
test: /\.pug$/,
use: ['html-loader', 'pug-html-loader']
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
use: ['file-loader?name=[name].[ext]&outputPath=images/&publicPath=images/',
'image-webpack-loader'
]
},
{
test: /\.(eot|ttf|woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
use: 'file-loader?name=[name].[ext]&outputPath=fonts/&publicPath=fonts/'
}
]
},
plugins: [
new htmlWebpackPlugin({
title: '',
template: './src/index.html',
minify: {
collapseWhitespace: true
},
hash: true,
inject: true
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
new MiniCssExtractPlugin({
filename: 'app.css',
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
})
]
};
Try this one and let me know what you got.

How to work with fonts and icons in webpack?

I needed to create webpack config for project where I use reactjs,semantic-ui-react and nucleo icons. It build almost everything except fonts and icons. I don't quite understand how to build them and nucleo icons dont display in project after build.My config:
const path = require('path');
const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const ASSETS_PATH = './assets';
const BUILD_DIR = path.resolve(__dirname, 'build');
var webpack_config = {
context: path.resolve(__dirname, ASSETS_PATH),
entry: {
main : [
"react",
"react-dom",
"react-props",
"redux",
"react-redux",
"redux-thunk"
],
module : "./js/module/index.jsx",
},
output: {
filename: '[name].min.js',
path: BUILD_DIR + '/js'
},
resolve: {
extensions: [' ','.js', '.jsx', 'css']
},
devtool: 'inline-source-map',
module : {
loaders : [
{
test : /\.jsx?/,
loader : 'babel-loader?compact=true&comments=true&minified=true',
query: {
presets:[
'es2015',
'react',
'stage-1'
]
},
exclude: /node_modules/
},
{
test: /\.(woff|woff2|eot|ttf|svg)(\?.*)?$/,
loader: 'file-loader?name=../css/fonts/[name].[ext]',
options: {
limit: 10000
}
},
{
test: /\.(png|jpe?g|gif)(\?.*)?$/,
loader: 'file-loader?name=../css/images/[name].[ext]'
},
{
test: /\.json$/,
loader: "json-loader"
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
}
]
},
plugins: [
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'production')
}
}),
new ExtractTextPlugin({
filename: "../css/style.min.css",
disable: false,
allChunks: true
}),
new OptimizeCssAssetsPlugin({
assetNameRegExp: /\.min\.css$/g,
cssProcessor: require('cssnano'),
cssProcessorOptions: { discardComments: { removeAll: true } },
canPrint: true
}),
new webpack.optimize.CommonsChunkPlugin({
names: ["main"]
}),
new webpack.optimize.UglifyJsPlugin({
minimize : true,
sourceMap : false,
beautify : false,
comments : false,
compress: {
warnings: false
}
})
]
};
module.exports = webpack_config;
So as a result I get js bundles in map 'js', I get css bundle style.min.css in css map. There also webpack creates images map, and puts jpg,png,svg. But font files(eot,ttf etc) he puts in js map with long names. How should I refactor my config in order to solve this problem?
Solved this problem with such loader structure(maybe will be usefull for somebody):
{
test: /\.(eot|svg|ttf|woff|woff2?)$/,
use: {
loader: 'file-loader'
, options: {
name: '../css/fonts/[name]-[hash:8].[ext]'
}
}
},

Categories

Resources