css-loader url() loads with `module.exports =`, Is there any options? - css

I made some apps that wrapper some site with custom css. but image is not shown.
This is my webpack.config.js module part.
module: {
rules: [
{
test: /\.css$/,
loaders: ['css-loader']
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'url-loader',
options: {
limit: 1000000 // 1000kb
}
}
]
},
}
Css look like this
.menu {
background-images: url("images/menu.png");
}
Some of issue with jQuery and Security(External Sites!), I put nodeIntegration: false in webPreferences
const css = require('./foo.css');
// ..
webContents.insertCSS(css.toString());
but launch a app, image is not shown. in console, I got this background-images url
background-image: url(data:image/jpeg;png,bW9kdWxl //...
decode base64 result is
module.exports = "data:image/png;base64 //...
I think module.exports cause this(Edit 3: Uncaught ReferenceError: module is not defined in console), because nodeIntegration: false
Is there any option to remove module.exports = in css-loader with other loaders? (or just turn nodeIntergration to true)?
It is same result on file-loader.
Edit 1: In my package.json: "css-loader": "^0.28.7", "url-loader": "^0.6.2", "webpack": "^3.8.1"
Edit 2: Maybe cuase by this in css-loader?

Related

Using LESS CSS with the latest Create React App

It seems like everything i'm finding online is old and doesn't seem to work for me.. Any help is appreciated.
I ran "npm run eject". Then I installed with NPM
"devDependencies": {
"less": "^3.12.2",
"less-loader": "^6.2.0"
},
and in my "webpack.config.js" file this is how i have it so far:
module: {
strictExportPresence: true,
rules: [
{
test: /\.less$/,
loader: 'less-loader', // compiles Less to CSS
},
// Disable require.ensure as it's not a standard language feature.
{ parser: { requireEnsure: false } },
// First, run the linter.
// It's important to do this before Babel processes the JS.
{
test: /\.(js|mjs|jsx|ts|tsx)$/,
enforce: 'pre',
use: [
{
options: {
cache: true,
formatter: require.resolve('react-dev-utils/eslintFormatter'),
eslintPath: require.resolve('eslint'),
resolvePluginsRelativeTo: __dirname,
},
loader: require.resolve('eslint-loader'),
},
],
include: paths.appSrc,
},
and then i get this error message when trying to run:
Failed to compile ./src/styles/index.less
(./node_modules/css-loader/dist/cjs.js!./node_modules/less-loader/dist/cjs.js!./node_modules/file-loader/dist/cjs.js??ref--7-oneOf-7!./src/styles/index.less)
module.exports = webpack_public_path +
"static/media/index.1f54121a.less";
^ Unrecognised input
Error in G:\Work Projects\uno\src\styles\index.less (line 1, column 15)
Hopefully this helps someonme. I found the answer here: https://segmentfault.com/a/1190000018858055
Short Version:
const cssRegex = /\.(css|less)$/;
const cssModuleRegex = /\.module\.(css|less)$/;
...
...
...
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use MiniCSSExtractPlugin to extract that CSS
// to a file, but in development "style" loader enables hot editing
// of CSS.
// By default we support CSS Modules with the extension .module.css
{
test: cssRegex, // edited to add less above
exclude: cssModuleRegex, // edited to add less above
use: getStyleLoaders({
importLoaders: 2, // changed from 1 to 2
modules: true, // added this line
sourceMap: isEnvProduction && shouldUseSourceMap,
},
'less-loader'),
// 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,
},
// Adds support for CSS Modules (https://github.com/css-modules/css-modules)
// using the extension .module.css
{
test: cssModuleRegex,
// etc

Svelte: Is there a way to make global css variables in scope of svelte components?

I have set my global.css file which I import in index.js
--root {
--main-color: red;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
index.js
import "./global.css";
import App from "./App.svelte";
const app = new App({
target: document.body
});
My webpack setup
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
entry: "./src/index.js",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "dist")
},
module: {
rules: [
{
test: /\.(html|svelte)$/,
exclude: /node_modules/,
use: {
loader: "svelte-loader",
options: {
emitCss: true,
hotReload: true
}
}
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: { loader: "style-loader", options: { sourceMap: true } },
use: [
{ loader: "css-loader", options: { sourceMap: true } },
{
loader: "postcss-loader",
options: {
sourceMap: true,
ident: "postcss",
plugins: loader => [
require("postcss-import")({}),
require("postcss-preset-env")(),
require("cssnano")()
]
}
}
]
})
}
]
},
plugins: [new HtmlWebpackPlugin(), new ExtractTextPlugin("styles.css")]
};
Works perfect for setting up global css for the entire app. But I am trying to use the --main-color in my svelte components. Is there a way to inject them down to all the components' css ?
Since I import global.css first, it should work as it emits a file with --root{} first then rest of the component styles.
You can place global styles under /routes/index.svelte file, like the example below:
<style>
:global(:root){
--header-color: purple
}
</style>
And simply use it anywhere like normally how you use CSS variables like so:
h1 {
color: var(--header-color);
}
I was busy with this, trying different webpack settings etc., seeing that the output css should work, I just could not find why it did not work. I wrote the post before trying for one last time, which wasted another hour. I finally found the error.
Instead of using :root{} I have mistyped it --root{}. I have posted it anyways, in case someone is stuck with the same mistake.

postcss-extract-media-query plugin is invalid

I'm trying to extract some media queries from my css bundles, but unfortunately plugin is not working.
ERROR in ./node_modules/css-loader!./node_modules/postcss-loader/src!./node_modules/jscrollpane/style/jquery.jscrollpane.css
Module build failed: TypeError: Invalid PostCSS Plugin found at: plugins[0]
Here is my postcss.config.js
const path = require('path');
module.exports = {
plugins: [
{
'postcss-extract-media-query': {
output: {
path: path.join(__dirname, 'dist'),
name: '[name]-[query].[ext]'
},
queries: {
'screen and (min-width: 1024px)': 'desktop'
}
}
}
]
}
Postcss works fine without it, at least I don't have any errors
Part of webpack.config.js, I doubt I have any problems here since it works fine
cssLoader = [ 'css-loader', 'postcss-loader'],
return {
module: {
rules: [ { test: /\.css$/, use: cssLoader },]
}
}
Part of my package.json
"postcss": "^7.0.14",
"postcss-extract-media-query": "^1.2.0",
"postcss-loader": "^3.0.0",
"webpack": "^3.12.0",
Do you have any idea why it's not working?
UPD:
I don't have any errors if I will use it as follows:
module.exports = {
plugins: [
require('postcss-extract-media-query'),
] }
But I need to set up some options as well, so it's not working for me

Webpack 4 - Style-loader/url not working

I'm having my webpack set up and it's running all fine, but in development it is serving my compiled scss stylesheets inline instead of using an URL.
module: {
rules: [
{
test: /\.scss$/,
use: [
{ loader: "style-loader"},
{ loader: "css-loader" },
{ loader: 'postcss-loader',
options: {
plugins: () => [require('autoprefixer')]
}
},
{ loader: "sass-loader" }
]
}
]
}
So I grabbed the docs and read up on how to use a single CSS file instead. I updated my webpack config to the following and since all loaders are running in reverse order this should be working;
module: {
rules: [
{
test: /\.scss$/,
use: [
{ loader: "style-loader/url"},
{ loader: "file-loader" },
{ loader: "css-loader" },
{ loader: 'postcss-loader',
options: {
plugins: () => [require('autoprefixer')]
}
},
{ loader: "sass-loader" }
]
}
]
}
It results in no errors, and inserts the following stylesheet into my header;
<link rel="stylesheet" type="text/css" href="6bbafb3b6c677b38556511efc7391506.scss">
As you can see it's creating an scss file, whereas I was expecting a .css file. I tried moving the file-loader around but that didn't work either and resulted in several crashes. Any idea how to turn this into a working css file?
I can't use mini-css-extract in my dev env since I'm using HMR. I already got this working on my prod env.
Update: When removing css-loader it compiles and shows my css applied to the page. But when I inspect the elements everything is on line 1 and the file it refers to can not be found
I'm importing my css like this in index.js by the way;
import '../css/styles.scss';
You can install extract-text-webpack-plugin for webpack 4 using:
npm i -D extract-text-webpack-plugin#next
The you can define the following constants:
// Configuring PostCSS loader
const postcssLoader = {
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: [
// Write future-proof CSS and forget old preprocessor specific syntax.
// It transforms CSS specs into more compatible CSS so you don’t need to wait for browser support.
require('postcss-preset-env')()
]
}
};
// Configuring CSS loader
const cssloader = {
loader: 'css-loader',
options: {
importLoaders: 1
}
};
Then in your SASS loader section, you can use the following:
ExtractTextPlugin.extract({
use: [cssloader, postcssLoader, 'sass-loader']
})
Then in you plugins section, you need to use the following:
new ExtractTextPlugin({
filename: 'css/[name].css'
)
Now suppose that your entry section is like below:
entry: {
app: 'index.js'
}
The generated CSS will be named as app.css and placed inside the css folder.
Another useful plugins for handling these type of post creating operations are:
HtmlWebpackPlugin and HtmlWebpackIncludeAssetsPlugin
Working with these plugins along with extract-text-webpack-plugin gives you a lot of flexibility.
I had a similar issue with webpack, after searching for a long time i found the soluton of combining a few plugins:
This is my result config: (as a bonus it preserves your sass sourcemaps;))
watch: true,
mode: 'development',
devtool: 'source-map',
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css", //make sure you use this format to prevent .scss extention in the hot reload file
chunkFilename: "[id].css"
})
],
module: {
rules: [
{
test: /\.scss$/,
use: [
'css-hot-loader', //5. this will hot load all the extracted css.
MiniCssExtractPlugin.loader, //4 this will extract all css
{
loader: "css-loader", //3. this is where the fun starts
options: {
sourceMap: true
}
},
{
loader: "postcss-loader", //2. add post css
options: {
sourceMap: true
}
},
{
loader: "sass-loader", //1 . you can ingore the globImporter
options: {
importer: globImporter(),
includePaths: ["node_modules"],
sourceMap: true
}
}
]
},
]
}

Webpack can't fix CSS override issue and bundle <style> elements in <head>

In my app, lets say I have two JS pages A and B, and each import a different stylesheet (import '../style/<A or B.css>').
Both stylesheets have identical classnames but but different properties.
I run yarn run dev ==> dev: webpack-dev-server --inline --hot ==> webpack -p
This is what my html <head> looks like
https://imgur.com/a/1JVb5
page A stylesheet is loaded first, then page B css style is loaded after
When I go to Page B, the css is correct
When I go to Page A, the css is mixed up and some class styles are overriden by page B.css.
My project structure is like
public/
bundle.js
index.html
src/
components/
pages/
style/
App.js
index.js
package.json
webpack.config.js
my webpack.config.js is
const path = require('path');
var config = {
entry: path.resolve(__dirname, 'src', 'index.js'),
output: {
path: path.resolve(__dirname, 'public'),
filename: 'bundle.js'
},
devServer: {
contentBase: path.resolve(__dirname, 'src'),
publicPath: path.resolve(__dirname, 'public')
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: [
{ loader: 'babel-loader',
options: { presets: ['react','env'] } }
]
},
{
test: /\.css$/,
use: [
{ loader: "style-loader?singleton",
options:
{ singleton: true }
},
{ loader: "css-loader" }
]
}
]
}
};
module.exports = config;
I want Webpack to merge the multiple elements and fix the css override issue
In Webpack, I have tried style-loader?singleton and { singleton: true } but it didnt work.
EDIT 1: looking into extract-text-webpack-plugin
EDIT 2:
import movieStyle from '../style/MovieDetail.css'
...
return (
<div id="CellDetail_right" className={ movieStyle['cell-detail-right'] }>...</div>
)
Ok, I added options: { modules: true } and it didnt work. My classNames are hyphenated and after compiling the browser renders the components WITHOUT any style or classes.
Div on browser looks like <div id="CellDetail_right">...<div>
One solution is to enable local scoped css to avoid styles bleeding/overrides.
Update your css-loader options to include modules: true
{
test: /\.css$/,
use: [
{
loader: "style-loader",
options: { singleton: true }
},
{
loader: "css-loader",
options: {
modules: true,
camelCase: 'dashes',
localIdentName: '[path][name]__[local]'
}
}
]
}
Then, using in your components as:
import styles from '../style/MovieDetail.css';
function MyComponent() {
return (
<div className={styles.container}>
<div className={styles.cellDetailRight}>Some Content</div>
</div>
);
}
This ensures that despite you have more .container rules defined in other css files, this particular rule becomes to something like ._-path-to-component__container.
Using camelCase: 'dashes' in options transform your hyphenated rules.
dashes in class names will be camelized
You can also review my webpack-demo project which includes configs to handle your scenario.
Check the webpack configurations
Read more on css-loader options

Resources