Cloudflare Deployment: Error: Cannot resolve module 'style-loader' - javascript

any idea how to fix this, the webpack config in the ckeditor folder is set like this:
const path = require("path");
const webpack = require("webpack");
const { bundler, styles } = require("#ckeditor/ckeditor5-dev-utils");
const CKEditorWebpackPlugin = require("#ckeditor/ckeditor5-dev-webpack-plugin");
const TerserWebpackPlugin = require("terser-webpack-plugin");
module.exports = {
devtool: "source-map",
performance: { hints: false },
entry: path.resolve(__dirname, "src", "ckeditor.js"),
output: {
// The name under which the editor will be exported.
library: "CKSource",
path: path.resolve(__dirname, "build"),
filename: "ckeditor.js",
libraryTarget: "umd",
libraryExport: "default",
},
optimization: {
minimizer: [
(compiler)=>{
const TerserPlugin = require('terser-webpack-plugin');
new TerserPlugin({
terserOptions: {
compress: {},
}
}).apply(compiler);
}
],
},
plugins: [
new CKEditorWebpackPlugin({
// UI language. Language codes follow the https://en.wikipedia.org/wiki/ISO_639-1 format.
// When changing the built-in language, remember to also change it in the editor's configuration (src/ckeditor.js).
language: "en",
additionalLanguages: "all",
}),
new webpack.BannerPlugin({
banner: bundler.getLicenseBanner(),
raw: true,
}),
],
module: {
rules: [
{
test: /\.svg$/,
use: ["raw-loader"],
},
{
test: /\.css$/,
use: [
{
loader: "style-loader",
options: {
injectType: "singletonStyleTag",
attributes: {
"data-cke": true,
},
},
},
{
loader: "css-loader",
},
{
loader: "postcss-loader",
options: {
postcssOptions: styles.getPostCssConfig({
themeImporter: {
themePath: require.resolve("#ckeditor/ckeditor5-theme-lark"),
},
minify: true,
}),
},
},
],
},
],
},
};
I tried to delete package-lock.json and delete node_modules and reinstall everything, but it did not work.
Tried other solutions from other Stack overflow questions that had similar issues, nothing worked
this happens for ckeditor by the way.

Related

How to bundle and minimize JS and CSS files with webpack

I have been trying to use webpack for my project. I have successfully got webpack to compile all of my js into one file correctly. But what i need is for it to also get the css. All of my css is in one file so i figured it would be easy but i cant figure it out. I have tried to split it up into 2 phases CSS_CONFIG and JS_CONFIG
const path = require('path');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const TerserPlugin = require("terser-webpack-plugin");
var JS_CONFIG = {
entry: path.join(__dirname, 'src/js/main.js'),
resolve: {
alias: {
'/components': path.resolve(__dirname, 'src/components/'),
'/js': path.resolve(__dirname, 'src/js/'),
'/views': path.resolve(__dirname, 'src/views/'),
},
},
optimization: {
minimizer: [
// For webpack#5 you can use the `...` syntax to extend existing minimizers (i.e. `terser-webpack-plugin`), uncomment the next line
new TerserPlugin(),
//new CssMinimizerPlugin(),
],
},
}
var CSS_CONFIG = {
entry:path.join(__dirname,"src/index.html"),
module: {
rules: [
{
test: /.s?css$/,
use: [],
},
],
},
optimization: {
minimize:true,
minimizer: [
// For webpack#5 you can use the `...` syntax to extend existing minimizers (i.e. `terser-webpack-plugin`), uncomment the next line
// `...`,
//new CssMinimizerPlugin(),
],
},
plugins: [],
}
module.exports = [JS_CONFIG, CSS_CONFIG];
This seems like it should be pretty straightforward with webpack but I must not be grasping somthing. Can anyone help me out?
I believe that your CSS_CONFIG should look more like this:
const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const RemoveEmptyScriptsPlugin = require('webpack-remove-empty-scripts');
const isDevelopment = process.env.NODE_ENV === 'development'
var config = {
module: {},
};
var cssConfig = Object.assign({}, config, {
devtool: 'source-map',
entry: {
main: path.resolve(__dirname, 'public/css/main.scss'),
fonts: path.resolve(__dirname, 'public/css/fonts.scss'),
app: path.resolve(__dirname, 'public/css/app.scss'),
},
output: {
path: path.resolve(__dirname, 'public/css')
},
performance: {
hints: false
},
plugins: isDevelopment ? [] : [
new RemoveEmptyScriptsPlugin(),
new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename: '[id].css'
}),
],
module: {
rules:[
// Extracts the compiled CSS from the SASS files defined in the entry
{
test: /\.scss$/,
use: isDevelopment ?
[
'style-loader',
{
loader: 'css-loader',
options: { sourceMap: true, importLoaders: 1, modules: false },
},
{
loader: 'postcss-loader',
options: { sourceMap: true }
},
{
loader: 'resolve-url-loader',
},
{
loader: 'sass-loader',
options: { sourceMap: true }
},
]
: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: (resourcePath, context) => {
// publicPath is the relative path of the resource to the context
// e.g. for ./css/admin/main.css the publicPath will be ../../
// while for ./css/main.css the publicPath will be ../
return path.relative(path.dirname(resourcePath), context) + "/";
},
},
},
{
loader: 'css-loader',
options: {
importLoaders: 2,
modules: false,
url: false,
},
},
{
loader: 'postcss-loader',
options:
{
postcssOptions:
{
plugins: [
require('postcss-import'),
require('postcss-url')({
url: 'copy',
useHash: true,
hashOptions: { append: true },
assetsPath: path.resolve(__dirname, 'public/assets/')
})
]
}
}
},
{
loader: 'resolve-url-loader',
},
{
loader: 'sass-loader',
options: { sourceMap: true }
},
]
},
/* you may or may not need this
{
test: /\.(woff(2)?|ttf|eot|svg)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/',
esModule: false,
}
}
]
},
*/
],
}
});
use runs the loaders in order that they are put in the array. So 'style-loader' needs to be executed first. Here is a simple way of achieving the desired result.
const path = require('path');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const TerserPlugin = require("terser-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const RemoveEmptyScriptsPlugin = require('webpack-remove-empty-scripts');
const isDevelopment = process.env.NODE_ENV === 'development'
var JS_CONFIG = {
entry: {
main: path.resolve(__dirname, 'src/js/main.js'),
css: path.join(__dirname, 'src/css/main.css'),
},
resolve: {
alias: {
'/components': path.resolve(__dirname, 'src/components/'),
'/js': path.resolve(__dirname, 'src/js/'),
'/views': path.resolve(__dirname, 'src/views/'),
},
},
module: {
rules:[
{
test: /\.css$/,
use:['style-loader','css-loader']
},
],
},
};
module.exports = [JS_CONFIG];

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's file loader doesn't copy images during production from /src to /dist

I have a Webpack setup which is split into 2 config files:
webpack.config.js handles the development portion which is fired using npx webpack-dev-server and webpack.config.prod.js respectively which handles the production by typing npm run build.
The development config works as expected, but the production one has one problem: everything works fine, but the images aren't copied and optimized from the source folder: src/images/sm , src/images/bg to dist/images/sm , dist/images/bg.
webpack.prod.js
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const path = require('path');
module.exports = function(){
return {
mode: 'development',
entry: [
'./src/app.js'
],
watch: true,
watchOptions: {
aggregateTimeout: 300, // Process all changes which happened in this time into one rebuild
poll: 1000, // Check for changes every second,
ignored: /node_modules/,
// ignored: [
// '**/*.scss', '/node_modules/'
// ]
},
devtool: 'source-maps',
devServer: {
contentBase: path.join(__dirname, 'src'),
watchContentBase: true,
host: '0.0.0.0',
hot: true,
open: true,
inline: true,
port: 9000
},
plugins: [
new HtmlWebpackPlugin({
title: 'Webpack starter project',
template: path.resolve('./src/index.pug')
}),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
}),
new webpack.HotModuleReplacementPlugin()
],
module: {
rules: [
{
test: /\.pug$/,
use: ['raw-loader', 'pug-html-loader'],
},
{
test: /\.scss$/,
use: [
'style-loader',
"css-loader",
"sass-loader"
]
},
{
test: /\.(jpg|jpeg|gif|png|svg|webp)$/,
use: [
{
loader: "file-loader",
options: {
outputPath: './images',
name: "[name].[ext]",
},
},
]
},
{
test: /\.html$/,
use: {
loader: 'html-loader',
}
},
]
}
};
}
webpack.config.prod.js
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const path = require('path');
module.exports = function(){
return {
mode: 'production',
entry: [
'./src/app.js'
],
optimization: {
minimizer: [
new OptimizeCSSAssetsPlugin()
]
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: 'Webpack starter project',
filename: 'index.html',
template: path.resolve('./src/index.pug')
}),
new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename: '[id].css'
}),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
}),
new webpack.HotModuleReplacementPlugin()
],
module: {
rules: [
{
test: /\.pug$/,
use: ['raw-loader', 'pug-html-loader'],
},
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader"
]
},
{
test: /\.(jpg|jpeg|gif|png|svg|webp)$/,
use: [
{
loader: "file-loader",
options: {
outputPath: './images',
name: "[name].[ext]",
},
},
{
loader: 'image-webpack-loader',
options: {
bypassOnDebug: true,
mozjpeg: {
progressive: false,
quality: 45
},
// optipng.enabled: false will disable optipng
optipng: {
enabled: true,
},
pngquant: {
quality: '65-90',
speed: 4
},
gifsicle: {
interlaced: true,
optimizationLevel: 3
},
// the webp option will enable WEBP
webp: {
quality: 20
}
}
},
],
},
{
test: /\.html$/,
use: {
loader: 'html-loader',
}
},
]
}
};
}
I uploaded my webpack setup to Google Drive and if anybody wants to check it out, here it is.
I googled all day and I don't see anything wrong with my code.
I tried other webpack configs and they have the same code as mine and their images get copied in the dist folder.
Can anyone help me figure this out?
Somebody on Reddit helped me. All I had to do was import the images in the app.js. Strangely, using other configs never required me to import the images, but I think that's because those configs were built using an older version of file loader.
I also changed the quality property since webpack expects an array instead of a string.
pngquant: {
quality: [0.65, 0.90],
speed: 4
}
To generate images in the dist folder under the same tree scheme as in the src I had to change this part :
{
loader: "file-loader",
options: {
name: "[path]/[name].[ext]",
context: "src"
},
},
Try with copy-webpack-plugin.
It worked for me.
I tried to like this.
First, you need to install the copy-webpack-plugin module.
npm install copy-webpack-plugin --save-dev
In webpack.config.js:
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports={
plugins: (
new CopyWebpackPlugin({
patterns: [
{from: "src/images", to: "images/"}
],
}),
)
}

Webpack Build Speed performance

The Webpack Bulid runs pretty slow, project background is a community portal developed in Vue.js...
Can anybody tell if there is any potential for improvement and if so, what?
I wonder if the time for the build process of 37401ms can still be changed by changing the codebase?
const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
const glob = require('glob');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const autoprefixer = require('autoprefixer');
const statsSettings = {
all: false,
modules: true,
maxModules: 0,
errors: true,
warnings: false,
moduleTrace: true,
errorDetails: true,
timings: true,
performance: true,
builtAt: true,
};
const {
rootDir,
srcDir,
assetsDir,
stylesDir,
buildDir,
sitepackageDir,
publicPath,
} = require('./config');
const chunks = glob.sync(path.join(rootDir, srcDir, 'pages/**/index.js'))
.reduce((obj, file) => {
const name = path.basename(path.dirname(file));
return {
...obj,
[name]: file,
};
}, {});
module.exports = env => {
return {
mode: env.production ? 'production' : 'development',
context: path.join(rootDir, srcDir),
entry: chunks,
output: {
path: path.join(rootDir, buildDir),
filename: '[name].js',
publicPath: env.production ? publicPath : '',
},
devtool: env.production ? false : 'cheap-module-eval-source-map',
devServer: {
contentBase: path.join(rootDir, buildDir),
inline: true,
proxy: {
'/api/v0': 'http://localhost:4000',
},
},
watchOptions: {
ignored: env.watch ? 'node_modules' : '',
aggregateTimeout: 300,
},
stats: env.watch ? statsSettings : 'normal',
module: {
rules: [
{
test: /\.vue$/,
include: [
path.join(rootDir, srcDir),
require.resolve('bootstrap-vue'),
],
loader: 'vue-loader',
},
{
test: /\.js$/,
include: [
path.join(rootDir, srcDir),
require.resolve('bootstrap-vue'),
],
loader: 'babel-loader',
},
{
test: /\.(css|scss)$/,
use: [
env.production ? MiniCssExtractPlugin.loader : 'vue-style-loader',
'css-loader',
{
loader: 'postcss-loader',
options: {
plugins: [
autoprefixer({
browsers: ['>1%', 'last 2 versions', 'not ie < 11'],
}),
],
},
},
{
loader: 'sass-loader',
options: {
includePaths: [
path.join(rootDir, srcDir, stylesDir),
],
},
},
],
},
{
test: /\.(jpg|jpeg|png|gif|webp|svg|eot|otf|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$/,
loader: 'file-loader',
options: {
name: `${assetsDir}/_processed_/[name].[hash:4].[ext]`,
},
},
],
},
optimization: {
runtimeChunk: {
name: '_runtime',
},
splitChunks: {
cacheGroups: {
// we need to figure out if it's worth having a common chunk
// or if each entry chunk should be somewhat self-contained
common: {
chunks: 'initial',
name: '_common',
minChunks: 2,
minSize: 0,
},
vendor: {
test: /node_modules/,
chunks: 'initial',
name: '_vendor',
enforce: true,
},
},
},
},
resolve: {
extensions: ['.js', '.json', '.vue'],
alias: {
'#app': path.join(rootDir, srcDir),
// although we're using single file components that can be pre-compiled,
// we want to dynamically mounting them in the DOM html.
// this is way we need to alias 'vue' to use the runtime + compiler build here.
// see: https://vuejs.org/v2/guide/installation.html#Runtime-Compiler-vs-Runtime-only
vue$: 'vue/dist/vue.esm.js',
},
},
plugins: [
new webpack.DefinePlugin({
PAGES: JSON.stringify(Object.keys(chunks)),
}),
new VueLoaderPlugin(),
...plugHtmlTemplates(),
...plugExtractCss(env),
...plugCopyAssets(),
],
};
};
function plugHtmlTemplates () {
return glob.sync(path.join(rootDir, srcDir, 'pages/**/template.html'))
.map(template => {
const name = path.basename(path.dirname(template));
return {
template,
filename: `${name}.html`,
chunks: ['_runtime', '_vendor', '_styles', '_common', name],
};
})
.map(htmlConfig => new HtmlWebpackPlugin(htmlConfig));
}
function plugExtractCss (env) {
if (!env.production) return [];
return [
new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename: '[name].css',
}),
];
}
function plugCopyAssets () {
const assetsSrcPath = path.join(rootDir, srcDir, assetsDir);
if (!fs.existsSync(assetsSrcPath)) return [];
return [
new CopyWebpackPlugin([
{ from: assetsSrcPath, to: path.join(rootDir, buildDir, path.basename(assetsDir)) },
// this is required for the icons to be selectable in the backend
{ from: path.join(assetsSrcPath, 'icons/'), to: path.join(rootDir, sitepackageDir, 'Resources/Public/Icons/') },
// this is required for avatars to be available; we must not check them in in fileadmin since they would
// prevent having the dir linked by Deployer during a deployment
{ from: path.join(rootDir, '../packages/users/Resources/Private/Images/Avatars/'), to: path.join(rootDir, buildDir, 'static/avatars/') },
]),
];
}
The question is whether you can improve the performance by using different plugins or summarizing steps...
I have a similar configuration. My configuration built ~33 seconds. I added a cache-loader package and decrease build time to ~17 seconds.
npm install --save-dev cache-loader
config:
rules: [
//rules here
{
test: /\.vue$/,
use: [
{
loader: 'cache-loader',
options: {}
},
{
loader: 'vue-loader',
options: vueLoaderConfig
}
],
},
{
test: /\.js$/,
use: [
{
loader: 'cache-loader',
options: {}
},
{
loader: 'babel-loader'
}
],
include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
}
]

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