Tools:
React 16.8.3
reactstrap 7.1.0
I followed the instructions here https://reactstrap.github.io/ but I'm still getting errors. I'm aware of this solution from their github page:
{ test: /\.css$/, loader: 'style-loader!css-loader' }
but that config file seems to be outdated. I'm only getting this error:
Module not found: Can't resolve 'style-loader!css-loader'
Here's my webpack config:
const getStyleLoaders = (cssOptions, preProcessor) => {
const loaders = [
isEnvDevelopment && require.resolve('style-loader'),
isEnvProduction && {
loader: MiniCssExtractPlugin.loader,
options: Object.assign(
{},
shouldUseRelativeAssetPaths ? { publicPath: '../../' } : undefined
),
},
{
loader: 'style-loader!css-loader',
options: cssOptions,
},
{
// Options for PostCSS as we reference these options twice
// Adds vendor prefixing based on your specified browser support in
// package.json
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebook/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
require('postcss-preset-env')({
autoprefixer: {
flexbox: 'no-2009',
},
stage: 3,
}),
],
sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
},
},
].filter(Boolean);
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
modules: true,
localIdentName: '[name]__[local]__[hash:base64:5]',
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
}),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
}
(I have no enough reputation to add a comment to your question)
well, I wanted to enable CSS modules so I ended up doing this.
It took me a while to figure out in the new version.
after you have successfully ejected, just only edit webpack.config.js file and add the two lines of code (check the code below)
....
....
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
modules: true, // add this line
localIdentName: "[name]__[local]__[hash:base64:5]", // add this line too
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment
}),
....
....
some more pics how to use CSS loaders:
my Layout.css file:
my Layout.js file:
Related
I have a fairly standard lerna monorepo setup, using yarn workspaces and TypeScript.
There are pacakge folders for various services and also the React frontend. I've been migrating the Webpack config to Webpack 5 so that I can take advantage of the module federation. The React app is complex, uses CSS modules with scss, TypeScript, etc so the config is relatively complex, nevertheless I feel as if I am there with compilation. That notwithstanding there are 2 issues that I cannot seem to fathom, the most problematic of them being that webpack seems to be trying to load files from other packages in the monorepo (and these are causing TypeScript/eslint errors).
Webpack.config.js
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const ForkTsCheckerWebpackPlugin = require("fork-ts-checker-webpack-plugin");
const ESLintPlugin = require("eslint-webpack-plugin");
const isDevelopment = process.env.NODE_ENV === "development";
const imageInlineSizeLimit = 2000;
// Default js and ts rules
const tsRules = {
test: /\.(js|mjs|jsx|ts|tsx)$/,
include: path.resolve(__dirname, "src"),
exclude: [/node_modules/],
loader: "babel-loader",
options: {
customize: require.resolve("babel-preset-react-app/webpack-overrides"),
presets: [
"#babel/preset-env",
"#babel/preset-react",
"#babel/preset-typescript",
],
plugins: [],
},
};
// Process any JS outside of the app with Babel.
// Unlike the application files, we only compile the standard ES features.
const externalJsRules = {
test: /\.(js|mjs)$/,
exclude: [/node_modules/],
loader: "babel-loader",
options: {
babelrc: false,
configFile: false,
compact: false,
presets: [
[
require.resolve("babel-preset-react-app/dependencies"),
{ helpers: true },
],
],
cacheDirectory: true,
cacheCompression: false,
},
};
let plugins = [
new ForkTsCheckerWebpackPlugin({
async: false,
}),
new ESLintPlugin({
extensions: ["js", "jsx", "ts", "tsx"],
}),
new MiniCssExtractPlugin({
filename: "[name].[contenthash].css",
chunkFilename: "[id].[contenthash].css",
}),
new HtmlWebpackPlugin({
template: path.resolve(__dirname, "public", "index.html"),
}),
new webpack.IgnorePlugin({
// #todo: this prevents webpack paying attention to all tests and stories, which probably ought only be done on build
resourceRegExp: /(coverage\/|\.spec.tsx?|\.mdx?$)/,
}),
];
if (isDevelopment) {
// For use with dev server
tsRules.options.plugins.push("react-refresh/babel");
externalJsRules.options.sourceMaps = true;
externalJsRules.options.inputSourceMap = true;
plugins = [...plugins, new webpack.HotModuleReplacementPlugin()];
}
module.exports = {
entry: path.resolve(__dirname, "src", "index.tsx"),
output: {
path: path.resolve(__dirname, "build"),
publicPath: "/",
clean: true,
},
module: {
rules: [
externalJsRules,
tsRules,
{
test: [/\.avif$/],
loader: "url-loader",
options: {
limit: imageInlineSizeLimit,
mimetype: "image/avif",
name: "static/media/[name].[hash:8].[ext]",
},
},
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: "url-loader",
options: {
limit: imageInlineSizeLimit,
name: "static/media/[name].[hash:8].[ext]",
},
},
{
test: /\.svg$/,
use: ["#svgr/webpack", "url-loader"],
},
{
test: /\.s?css$/,
oneOf: [
{
test: /\.module\.s?css$/,
use: [
isDevelopment
? // insert css into DOM via js
"style-loader"
: // insert link tags
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
modules: true,
sourceMap: isDevelopment,
importLoaders: 2,
},
},
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: [
"postcss-flexbugs-fixes",
[
"postcss-preset-env",
{
autoprefixer: {
flexbox: "no-2009",
},
stage: 3,
},
],
"postcss-normalize",
],
},
},
},
{
loader: "sass-loader",
options: {
sourceMap: isDevelopment,
},
},
],
},
{
use: [
isDevelopment
? // insert css into DOM via js
"style-loader"
: // insert link tags
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
sourceMap: isDevelopment,
importLoaders: 2,
},
},
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: [
"postcss-flexbugs-fixes",
[
"postcss-preset-env",
{
autoprefixer: {
flexbox: "no-2009",
},
stage: 3,
},
],
"postcss-normalize",
],
},
},
},
{
loader: "sass-loader",
options: {
sourceMap: isDevelopment,
},
},
],
},
],
},
],
},
resolve: {
extensions: [".tsx", ".ts", ".js", ".scss"],
symlinks: false,
// don't provide polyfills for non UUI-core
fallback: {
// crypto: false,
// fs: false,
// stream: false,
// path: false,
},
},
optimization: {
runtimeChunk: true,
},
plugins: [...plugins],
devtool: "eval-cheap-module-source-map",
devServer: {
static: path.join(__dirname, "build"),
historyApiFallback: true,
port: 3000,
open: true,
hot: true,
},
};
Webpack is run from the frontend package folder. Also I have scanned the code for any refrences to other packages in the React code, but there are none, so I can't understand why this is loading and how to prevent them loading.
Example error:
ERROR in ../../node_modules/#githubpackage/src/aFile.ts:2:25
TS2801: This condition will always return true since this 'Promise<boolean>' is always defined.
Help much appreciated (I realise the issue should be fixed too ;p).
[EDIT] I've edited the error to indicate that the problematic package is the only package that I am installing via github packages (in a couple of the other monorepo packages).
ALSO I edited the entry file so that it only imported React and ReactDOM and rendered a <p> tag and webpack still tried loading this package... so unless there is something wrong with the webpack config, this is some odd behaviour.
Hi I ejected CRA to add less config but i'm getting error like this
(./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-3-1!./node_modules/less-loader/dist/cjs.js??ref--6-oneOf-3-2!./node_modules/postcss-loader/src??postcss!./src/index.css)
webpack version -4 ,I added the less configuration any way but getting error ,and also i have installed bootstrap css and it also getting error like "{" missing in cli
const getStyleLoaders = (cssOptions, preProcessor) => {
const loaders = [
isEnvDevelopment && require.resolve('style-loader'),
isEnvProduction && {
options: paths.publicUrlOrPath.startsWith('.')
? { publicPath: '../../' }
: {},
},
{
loader: require.resolve('css-loader'),
options: cssOptions,
},
{
loader: require.resolve('less-loader'), //added less here
options: cssOptions,
},
{
loader: require.resolve('postcss-loader'),
options: {
ident: 'postcss',
plugins: () => [
require.resolve('autoprefixer'),
require('postcss-flexbugs-fixes'),
require('postcss-preset-env')({
autoprefixer: {
flexbox: 'no-2009',
},
stage: 3,
}),
postcssNormalize(),
],
sourceMap: isEnvProduction && shouldUseSourceMap,
},
},
And in resolve
//less loader
{
test:'/\.less$/',
include: lessModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
},
'less-loader'
),
sideEffects: true,
},
{
test: /\.module\.less$/,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: {
getLocalIdent: getCSSModuleLocalIdent,
},
},
'less-loader'
),
},
How to add less in CRA?
To me it was solved by adding this rule (just that, no need more changes in webpack.config.js) :
{
test: /\.less$/,
use: getStyleLoaders(
{
importLoaders: 3,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: {
getLocalIdent: getCSSModuleLocalIdent,
},
},
'less-loader'
),
},
Also, Make sure that you're using the latest version of less-loader
I'm getting an error for css loader invalid option and my webpack.conifg.js code is as follows :
const path = require('path');
const HtmlWebPackPlugin = require("html-webpack-plugin");
const htmlWebpackPlugin = new HtmlWebPackPlugin({
template: "./public/index.html"
});
module.exports = {
entry: "./src/index.js",
output: {
path: path.resolve('dist'),
filename: 'bundled.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
use: [
{
loader: "style-loader"
},
{
loader: "css-loader",
options: {
modules: true,
importLoaders: 1,
localIdentName:"[name]_[local]_[hash:base64]",
sourceMap: true,
minimize: true
}
}
]
},
{
test: /\.(png|jpg|woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader?limit=100000'
}
]
},
plugins: [htmlWebpackPlugin]
};
I don't know where I'm doing wrong.Please help me to solve this issue. I'm using webpack for reactjs 4 and webpack version is 4. Thanks
This is what resolved my case:
css-loader 2.1.1
{ loader: 'style-loader'},
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[local]',
import: true,
importLoaders: true,
}
},
{ loader: 'sass-loader'}
css-loader 3.0.0
{ loader: 'style-loader'},
{
loader: 'css-loader',
options: {
modules: {
mode: 'local',
localIdentName: '[local]',
},
import: true,
importLoaders: true,
}
},
{ loader: 'sass-loader'}
Try commenting out:
// minimize: true
Commenting out minimize worked previously, though I began a new project with a fresh install of css-loader, and the culprit this time around is importLoader: 1. Just remove importLoader and it should work.
I'm using css modules with React, and everything is running properly.
This worked for my VUE Js project:
Browse to the /build/utils.js file and in the object of thecss-loader comment on the option that is marking you in the error. In my case I had to comment:
minimize: process.env.NODE_ENV === 'production',
I've been struggling with getting my source-maps working in my app for quite a while. I have set
devtool: 'source-map',
in the webpack configuration, but they are still not available in the Chrome devtools.
I pushed a really simple app using my FE Stack hoping someone could identify the issue, whether it is with webpack, angular, or some other library. https://github.com/coreysnyder/Angular-Webpack3-Seed
Here are the versions I'm running:
{
CoreyApp: '1.0.0',
npm: '4.4.4',
ares: '1.10.1-DEV',
http_parser: '2.7.0',
icu: '57.1',
modules: '48',
node: '6.9.0',
openssl: '1.0.2j',
uv: '1.9.1',
v8: '5.1.281.84',
zlib: '1.2.8'
}
OSX 10.12.6
You will probably have to setup source map for different loaders individually.
For 'ng-annotate-loader' (Docs)
use: [{
loader: 'ng-annotate-loader',
options: {
add: true,
single_quotes: true ,
map: { inline: true, inFile: 'app.js', sourceRoot: __dirname + '/app' }}
}]
For less you can use documentation option like #ahmedelgabri suggested
use: [{
loader: "style-loader"
}, {
loader: "css-loader", options: {
sourceMap: true
}
}, {
loader: "less-loader", options: {
sourceMap: true
}
}]
Old post before OP github changes.
Other option is to add devtoolLineToLine: true in your output, if you want to use devtool: 'source-map'. But devtoolLineToLine is deprecated, so consider changing devtool to something else. devtool: 'source-map' demo image
output: isTest ? {} : {
devtoolLineToLine: true, // <= this line
sourceMapFilename: '[name].map',
path: __dirname + '/dist',
filename: '[name].bundle.js',
publicPath: publicPath
},
Alternatively you could use devtool: 'eval' or some variation of eval, like cheap-module-eval-source-map (similar behavior, but without file names) also works fine for me
I could fix your source maps for JS files, by adding the babel-loader. To do this, you need to install babel-loader:
npm i -D babel-loader#8.0.0-beta.0 #babel/core #babel/preset-env
and then extend your rule for .js
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'ng-annotate-loader',
options: { add: true, single_quotes: true }
},
{
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
]
}, [...]
]
Ready further details on babel-loader github repo
There is nothing wrong with the Webpack config here https://github.com/coreysnyder/Angular-Webpack3-Seed
here is a gif using your code & setting a breakpoint in view1 file
And here is why the text is blue
And I can see the source just fine
The main issue is the less-loader you need to pass the source-maps options for both, the less-loader & css-loader check the readme
{
test: /\.less$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
sourceMap: true,
},
},
{
loader: 'less-loader',
options: {
sourceMap: true,
},
},
],
},
After doing this you will be able to debug from the styles panel like this
If you want to edit directly the .less files the readme mentions a blog post that can help with this https://github.com/webpack-contrib/less-loader#source-maps
I hope this answers your question
I have an issue with upgrading to webpack 2 and the extract text plugin. I have the dev version (without this plugin) working and I cant see whats different. The error I get is
node_modules\webpack\lib\Chunk.js:62
return this.entrypoints.length > 0;
TypeError: Cannot read property 'length' of undefined
I have gulp running webpack 2 and this plugin for a single css file. This is the main part of my webpack config (happy to provide it all if needed):
...
modules: { rules :[ ... {
test: /\.scss/,
exclude: /node_modules/,
use: [
"style-loader?sourceMap",
{
loader: "css-loader",
options: {
minimize: true,
modules: true,
importLoaders: true,
localIdentName: "[path]___[name]__[local]___[hash:base64:5]",
},
},
{
loader: "postcss-loader",
options: { ...postCSSConfig },
},
{
loader: "sass-loader",
options: { includePaths: [path.join(process.cwd(), "src", "Styles", "Includes")] },
},
],
}, ]},
plugins: [
new ExtractTextPlugin({
filename: "[contenthash].css",
allChunks: true,
}), ...
Im using the following versions:
Webpack: 2.3.3
Extract text plugn: 2.0.1
Edit: Here is my entry point,
context: path.resolve(process.cwd(), "./src/"),
entry: [
"babel-polyfill",
"whatwg-fetch",
"Boot",
],
devtool: "eval",
resolve: {
modules: ["src", "node_modules"],
extensions: [".js", ".jsx"],
},
Any ideas would be great.
Thanks in advance.
According to docs, you also have to create proper rule for loading styles.
Please take a look at that, it's my rule. Please let me know if it helped you.
{
test: /\.(scss|css)$/,
exclude: /node_modules/
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'postcss-loader', 'sass-loader']
})
}
Anyway, yet I didn't manage to use ExtractTextPlugin with sourceMaps, so I can't give you solution to use this plugin with source maps.