webpack bundling multiple css imports from js file - javascript

This is a part of my list of imports in my app.js file:
import "jsgrid"
import "./../node_modules/jsgrid/dist/jsgrid.css";
import "./../node_modules/jsgrid/dist/jsgrid-theme.css";
import "jstree";
import "./../node_modules/jstree/dist/themes/default/style.css";
and this is my webpack.config:
var path = require('path');
const webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
//var SplitChunksPlugin = require('webpack.optimization.splitChunks');
var LiveReloadPlugin = require('webpack-livereload-plugin');
const autoprefixer = require('autoprefixer');
module.exports = {
entry:{
app: [ './src/app.scss', 'jquery', './src/app.js']
},
devtool: 'inline-source-map',
externals: /^(tables.)/i,
module: {
rules:
[
{
test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000'
},
{
test: /\.(css)$/,
use: [
{
loader: 'file-loader',
options: {
name: 'bundle-css.css',
},
},
{loader: 'extract-loader'},
{loader: 'css-loader'},
{loader: 'postcss-loader',
options: {
plugins: () => [autoprefixer()],
},
},
],
},
{
test: /\.(scss)$/,
use: [
{
loader: 'file-loader',
options: {
name: 'bundle-sass.css',
},
},
{loader: 'extract-loader'},
{loader: 'css-loader'},
{loader: 'postcss-loader',
options: {
plugins: () => [autoprefixer()],
},
},
{
loader: 'sass-loader',
options: {
includePaths: ['./node_modules'],
},
}],
},
{
test: /\.js$/,
include: /src/,
loader: 'babel-loader',
query: {
presets: ['es2015'],
},
}],
},
/*optimization: {
splitChunks: {
chunks: "initial"
}
},*/
optimization: {
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all'
}
}
}
},
plugins: [
new ExtractTextPlugin('style.css'),
new LiveReloadPlugin({}),
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', jquery: 'jquery' })
/*new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./dist/vendor-manifest.json')
})*/
],
resolve: {
extensions: ['.js']
},
watch: true,
watchOptions: {
aggregateTimeout: 300,
//ignored: /node_modules/
},
output: {
publicPath: './dist',
filename: 'bundle.js',
path: path.resolve(__dirname, './dist')
}
};
Now the problem is that webpack only seems to take into account the first .css file in my list of imports, ignoring the rest.
So as of now, webpack would only compile jsgrid.css into my bundle-css.css. But if I comment this line: import "./../node_modules/jsgrid/dist/jsgrid.css"; then webpack would only compile jsgrid.theme into my bundle.css.
I have been searching for the issue for quite some time now, but have not found anything.

Your config was totally wrong, see the changes i've done:
const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); // <-------- run npm install --save-dev mini-css-extract-plugin
const LiveReloadPlugin = require('webpack-livereload-plugin');
const autoprefixer = require('autoprefixer');
module.exports = {
entry:{
app: './src/app.js'
},
devtool: 'inline-source-map',
externals: /^(tables.)/i,
module: {
rules:
[
{
test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000'
},
{
test: /\.(css)$/,
use: [
MiniCssExtractPlugin.loader, // <---- added here
'css-loader',
{
loader: 'postcss-loader',
options: {
plugins: () => [autoprefixer()],
}
}
],
},
{
test: /\.(scss)$/,
use: [
MiniCssExtractPlugin.loader, // <--- added here
'css-loader',
{
loader: 'postcss-loader',
options: {
plugins: () => [autoprefixer()],
},
},
'sass-loader'
],
},
{
test: /\.js$/,
include: /src/,
loader: 'babel-loader',
query: {
presets: ['es2015'],
},
}],
},
/*optimization: {
splitChunks: {
chunks: "initial"
}
},*/
optimization: {
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all'
}
}
}
},
plugins: [
new MiniCssExtractPlugin({
filename: 'style.css'
}),
new LiveReloadPlugin({}),
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', jquery: 'jquery' })
/*new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./dist/vendor-manifest.json')
})*/
],
resolve: {
extensions: ['.js']
},
watch: true,
watchOptions: {
aggregateTimeout: 300,
//ignored: /node_modules/
},
output: {
publicPath: './dist',
filename: 'bundle.js',
path: path.resolve(__dirname, './dist')
}
};

Related

Webpack shows white screen

After I've added webpack in my react app, once the webpack started, it shows the white screen, and the whole bundle gets downloaded at one time. Even though I've done code splitting in react.
my webpack config:
/* eslint-disable no-un`enter code here`def */
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const HtmlWebpackInjectPreload = require("#principalstudio/html-webpack-inject-preload");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
module.exports = {
entry: path.resolve(__dirname, './index.js'),
devtool: "inline-source-map",
output: {
path: path.resolve(__dirname, "build"),
filename: "bundle.js",
publicPath: '/'
},
devServer: {
contentBase: path.resolve(__dirname, 'build'),
port: 4000,
hot: true,
},
resolve: {
extensions: [".*",".js", ".jsx", ".css"],
fallback: {
stream: false
}
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules)/,
use: ["babel-loader"],
},
{
test: /\.css$/,
exclude: /\.module\.css$/,
use: ["style-loader", "css-loader"],
},
{
test: /\.module\.css$/,
use: [
"style-loader",
{
loader: "css-loader",
options: { importLoaders: 2, modules: true },
},
"postcss-loader",
],
},
{
test: /\.(jpe?g|png|gif|woff|woff2|eot|ttf|svg)(\?[a-z0-9=.]+)?$/,
use: [
{
loader: "url-loader",
options: {
limit: 8192,
},
},
],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve('./index.html')
}),
new CleanWebpackPlugin(),
new HtmlWebpackInjectPreload({
files: [
{
match: /.*\.woff2$/,
attributes: { as: "font", type: "font/woff2", crossorigin: true },
},
{
match: /\.[a-z-0-9]*.css$/,
attributes: { as: "style" },
},
],
}),
],
};
The attached bundle image also gets larger up to 19MB. What's going wrong I'm not able to figure out.

React + Webpack: "RuntimeError: memory access out of bounds"

I've recently developed a react + webpack application that is deployed using
AWS Amplify. I've been getting a strange error that is logged on Sentry, but can't
find a way to replicate the bug.
RuntimeError: memory access out of bounds
I suspect it has something to do with my webpack configuration, but I don't know whats wrong.
I never used wasm, but it seems to be related to it.
Here is my production level webpack configuration.
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const env = require('../environment/prod.env');
const commonPaths = require('./paths');
const webpack = require('webpack');
const SentryWebpackPlugin = require('#sentry/webpack-plugin');
module.exports = {
mode: 'production',
devtool: 'source-map',
output: {
filename: `${commonPaths.jsFolder}/[name].[hash].js`,
path: commonPaths.outputPath,
chunkFilename: `${commonPaths.jsFolder}/[name].[chunkhash].js`,
},
optimization: {
minimizer: [
new TerserPlugin({
parallel: true,
cache: true,
sourceMap: true,
}),
new OptimizeCSSAssetsPlugin(),
],
splitChunks: {
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'initial',
},
async: {
test: /[\\/]node_modules[\\/]/,
name: 'async',
chunks: 'async',
minChunks: 4,
},
},
},
runtimeChunk: true,
},
module: {
rules: [
{
test: /\.scss$/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
sourceMap: true,
},
},
{
loader: 'sass-loader',
options: {
sourceMap: true,
},
},
],
},
{
test: /\.css$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
sourceMap: true,
},
},
],
},
],
},
plugins: [
new webpack.DefinePlugin({
'process.env': env,
}),
new MiniCssExtractPlugin({
filename: `${commonPaths.cssFolder}/[name].css`,
chunkFilename: `${commonPaths.cssFolder}/[name].css`,
}),
],
};
Here is also my common webpack configuration
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const commonPaths = require('./paths');
module.exports = {
context: commonPaths.srcPath,
entry: commonPaths.entryPath,
output: {
path: commonPaths.outputPath,
filename: 'js/[name].js',
},
resolve: {
extensions: ['.ts', '.js', '.html', '.vue'],
alias: {
'~': commonPaths.srcPath,
},
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
include: commonPaths.srcPath,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
plugins: ['react-hot-loader/babel'],
},
},
{
test: /\.(png|jpg|gif|svg)$/,
use: [
{
loader: 'file-loader',
options: {
name: 'assets/img/[name].[hash:8].[ext]',
publicPath: '/',
},
},
],
},
{
test: /\.(mp3)$/,
use: [
{
loader: 'file-loader',
options: {
name: 'assets/audio/[name].[hash:8].[ext]',
publicPath: '/',
},
},
],
},
{
test: /\.(ttc|ttf|eot)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: [
{
loader: 'file-loader',
options: {
name: 'assets/fonts/[name].[hash:8].[ext]',
publicPath: '/',
},
},
],
},
],
},
serve: {
content: commonPaths.entryPath,
dev: {
publicPath: commonPaths.outputPath,
},
open: true,
},
resolve: {
modules: ['src', 'node_modules', 'bower_components', 'shared', '/shared/vendor/modules'],
extensions: ['*', '.js', '.jsx'],
},
plugins: [
new webpack.ProgressPlugin(),
new HtmlWebpackPlugin({
favicon: './icon.png',
template: commonPaths.templatePath,
}),
new ScriptExtHtmlWebpackPlugin({
defaultAttribute: 'async',
}),
],
};
Any help would really help. Thanks.
Try to restart your server and make sure you reinstall node modules.

Setting up file-loader in webpack produces error during build time

This is how my webpack.config.babel.js looks like:
import path from 'path'
import MiniCssExtractPlugin from 'mini-css-extract-plugin'
const out = path.resolve(__dirname, './dist')
const client = path.resolve(__dirname, './src/client')
export default {
entry: {
main: `${client}/index`,
plugins: `${client}/plugins`
},
output: {
path: `${out}`,
filename: 'js/[name].js',
chunkFilename: 'js/[name].js'
},
module: {
rules: [
{
test: /\.jsx?/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.scss$/,
use: ['style-loader', MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'sass-loader']
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
name: 'assets/img/[name].[ext]'
}
}
]
}
]
},
optimization: {
runtimeChunk: {
name: 'manifest'
},
splitChunks: {
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
priority: -20,
chunks: 'all'
}
}
}
},
target: 'web',
cache: true,
plugins: [
new MiniCssExtractPlugin({
filename: 'css/[name].css'
})
]
}
So as you can see i'm using file-loader for png, svg, gif, and jpg.
I then import the image like this:
import img404 from '../../assets/img/404-error.svg'
but I keep getting this error:
I'm not really sure what I am doing wrong here :(
FYI: This actually saves the image in dist/assets/img/THE_ACTUAL_IMAGE_FILE as expected

babel transpile to es5 doesnt work for node_modules

I am trying to run my current project in ie11, but it gives me an error saying SCRIPT1002: syntax error in foundation.js (its part of google's material design classes). The line in question is export default MDCFoundation. Now from what i have red the issue is that this is es6 code and ie11 only supports es5. So far so good. The problem now is I cant seem to figure out how to tell babel to transpile to es5. I am using webpack and babel, here is my webpack.config.js:
var path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
var LiveReloadPlugin = require('webpack-livereload-plugin');
const autoprefixer = require('autoprefixer');
module.exports = {
entry:{
app: ['./src/app.js']
},
devtool: 'inline-source-map',
externals: /^(tables.)/i,
module: {
rules:
[
{
test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000'
},
{
test: /\.(css)$/,
use: [
MiniCssExtractPlugin.loader, // <---- added here
'css-loader',
{
loader: 'postcss-loader',
options: {
plugins: () => [autoprefixer()],
}
}
],
},
{
test: /\.(scss)$/,
use: [
MiniCssExtractPlugin.loader, // <--- added here
'css-loader',
{
loader: 'postcss-loader',
options: {
plugins: () => [autoprefixer()],
},
},
{
loader: 'sass-loader',
options: {
includePaths: ['./node_modules'],
},
}
],
},
{
test: /\.js$/,
include: /src/,
loader: 'babel-loader',
options: {
"presets": [
["env", {
"targets": {
"browsers": ["ie >= 11"]
}
}]
]
}
}
],
},
optimization: {
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all'
}
}
}
},
plugins: [
new MiniCssExtractPlugin({filename: 'style.css'}),
new LiveReloadPlugin({}),
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', jquery: 'jquery' })
],
resolve: {
extensions: ['.js']
},
watch: true,
watchOptions: {
aggregateTimeout: 300,
},
output: {
publicPath: './dist',
filename: 'bundle.js',
path: path.resolve(__dirname, './dist')
}
};
As you can see I am already trying to tell babel to transpile for ie11, but it still gives me the same error.

How to use Sass-loader with React and Webpack?

I'm using React 16, Webpack 3 and Bootstrap 4 beta.
I'm trying to load .scss files into React using something similar to the following import styles from './styles/app.scss'. At the moment I am using import style from 'style-loader!css-loader!sass-loader!applicationStyles';. I would like to move away from using the sass-loader in the .js file.
Any help improving up my webpack config would also be most welcome as it's a mess...
Here's my webpack file:
const webpack = require('webpack');
const path = require('path');
const envFile = require('node-env-file');
require('babel-polyfill');
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
try {
envFile(path.join(__dirname, 'config/' + process.env.NODE_ENV + '.env'))
} catch (e) { }
module.exports = {
entry: [
'script-loader!jquery/dist/jquery.min.js',
'babel-polyfill',
'whatwg-fetch',
'./app/app.jsx',
],
externals: {
jQuery: 'jQuery'
},
plugins: [
new webpack.ProvidePlugin({
'$': 'jQuery',
'jQuery': 'jQuery',
'window.jQuery': 'jquery',
Popper: ['popper.js', 'default'],
}),
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } }),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV),
API_KEY: JSON.stringify(process.env.API_KEY),
API_DOMAIN: JSON.stringify(process.env.API_DOMAIN),
API_FILE_DOMAIN: JSON.stringify(process.env.API_FILE_DOMAIN),
}
}),
],
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js',
publicPath: '/'
},
resolve: {
modules: [
__dirname,
'node_modules',
'./app/api',
'./app/constants',
],
alias: {
applicationStyles: 'app/styles/app.scss'
},
extensions: ['.js', '.jsx']
},
devServer: { historyApiFallback: { index: 'public/index.html' }, },
module: {
loaders: [
{
loader: 'babel-loader',
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/
},
// {
// loader: 'sass-loader',
// options: {
// includePaths: [ path.resolve(__dirname, './node_modules/bootstrap/scss')]
// },
// test: /\.scss?$/,
// },
{
loader: 'css-loader',
options: {
includePaths: [path.resolve(__dirname, './node_modules/react-table/react-table.css')]
},
test: /\.css?$/,
}
],
// I tried this but it gave me an error
// rules:[
// {
// test: /\.scss$/,
// use: [
// { loader: "style-loader" },
// { loader: "css-loader" },
// { loader: "sass-loader" }
// ]
// }
// ],
},
devtool: process.env.NODE_ENV === 'production' ? undefined : 'eval-source-map'
};
Here are the imports in my App.jsx file
import 'bootstrap'
import style from 'style-loader!css-loader!sass-loader!applicationStyles';
import 'style-loader!react-table/react-table.css';
I added rules to my webpack - see below:
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: { loader: 'babel-loader'}
},
{
test: /\.css?$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
]
},
{
test: /\.scss$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
{ loader: "sass-loader" }
]
},
]
},
so now I can just do:
import style from 'applicationStyles';
import 'react-table/react-table.css';
Make it more simple.
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module: {
rules: [
{
test: /\.(css|scss)$/,
use: ['style-loader', MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
},
],
},
{
test: /\.s[ac]ss$/i,
use: [
{
loader: "style-loader",
},
{
loader: "css-loader",
options: {
modules: true,
localsConvention: "camelCase",
sourceMap: true,
},
},
{
loader: "sass-loader",
options: {
sourceMap: true,
},
},
],
}
}

Categories

Resources