hey people I need help with the following:
am creating React UI component library
I am using webpack and dev build works great, scss files are loaded and components are displayed correctly
on production build, JS bundle is created as well as CSS (I use SCSS) bundle
BUT when I install the library in another React project and import the component, CSS is not loaded (cmp is not styled), JS works fine and the component is rendered yet styles are not loaded...
EDIT
Apparently this approach requires manual loading of CSS in parent app project. Which I want to avoid. Is there alternative way which can provide scenario in which styles will be resolved on the level on component without need for manual loading?
Here is my production webpack config:
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.join(__dirname, '../lib'),
libraryTarget: 'commonjs',
},
module: {
rules: [
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader']
})
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader']
})
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
},
{
test: /\.svg/,
use: {
loader: 'svg-url-loader',
options: {}
}
}
]
},
externals: {
'react': 'commonjs react',
'react-dom': 'commonjs react-dom',
},
resolve: {
modules: [
path.resolve('./src'),
path.resolve('./node_modules')
]
},
plugins: [
new ExtractTextPlugin({
filename: 'ui-library.css'
})
]
};
You could simply not use ExtractTextPlugin.
The whole purpose of Webpack is to group assets not based on file type but by a component perspective.
So, if you remove ExtractTextPlugin, your CSS will be included in your .js bundle.
Related
I have gone through a lot of questions on stackoverflow and article before writing this question here.
I am successfully able to create the CSS file sass using webpack4.
I have file as below client.js, it import the scss
import React , { Component } from 'react'
import { connect } from 'react-redux';
import './jobcard.scss';
here is my webpack config.
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: {
client: './src/client.js',
},
output: {
path: path.resolve(__dirname, 'asset'),
filename: "[name].js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
},
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader"
]
},
]
},
plugins: [
new MiniCssExtractPlugin({
filename: 'main.css',
})
]
}
It successfully creating the main.css and store in the '/asset' folder.
but the problem is when I complied client.js using babel. it has below the line.
require("./jobcard.scss");
its breaks due to the above line because in dist folder there is no such scss file as it's extract and placed in 'asset' folder. I want my css/image in 'asset' folder.
my expectation is my final css moved to '/asset' folder which is happening right now and the above line should get removed from complied client.js file.
So I can refer the main.css on my index.html from asset location.
Try with this config to see if it work for you
module: {
rules: [{
test: /\.scss$/,
use: [
'style-loader',
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
minimize: true,
sourceMap: true
}
},
{
loader: "sass-loader"
}
]
}
]
}
I am writing an electron app using react as for the UI and webpack for bundling. Webpack is configured right now for the react part of the application as follows:
const path = require('path');
const HtmlWebPackPlugin = require("html-webpack-plugin");
const CopyWebpackPlugin = require('copy-webpack-plugin')
module.exports = {
mode: 'development',
entry: './src/index.tsx',
target:'node',
output: {
filename: '[name].bundle.js',
path: path.join(__dirname, 'build')
},
module: {
rules: [
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: {
loader: 'ts-loader'
}
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader'
}
]
},
{
test: /\.css$/,
loader: 'css-loader',
options: {
sourceMap: true,
},
},
{
test: /\.scss$/,
use: [{
loader: "css-loader", options: {
sourceMap: true
}
}, {
loader: "sass-loader", options: {
sourceMap: true
}
}]
}
]
},
resolve: {
extensions: ['.tsx', '.ts', '.js']
},
plugins: [
new HtmlWebPackPlugin({
template: "./index.html",
filename: "./index.html"
}),
new CopyWebpackPlugin([{ from: 'public',ignore: ['*.html'] }])
],
devtool: 'eval-source-map'
}
In my index.html I need to use the following script tag for electron's rendering process :
<script>
require('build/bundle.js')
</script>
When I run webpack-dev-server everything compiles without error, but when I open chrome dev tools I see this error :
Uncaught ReferenceError: require is not defined
at (index):12
I had to target node in my webpack.config to make electron work so I assume the require function works in browser as well since if I were to create an electron app in a pure node.js environment(without webpack and react) it works without any additional configuration. So I guess there is an issue with my webpack configuration, but I can't find any useful resource online unfortunately. Can anyone help me out? Thanks in advance!
Electron is basically a chromium browser connected to a node process through « IPC ».
This means you don’t have require available in the browser.
You need to import your script like this:
<script src="/build/bundle.js"></script>
And also you need to change the target from node to electron-renderer for the browser code.
If you also need to build code for the node side you need to add the electron-main target.
See https://webpack.js.org/configuration/
First. I know questions like this were asked, but I am missing something to understand them. I am trying to compile scss to css. And I would like webpack to basically do the same as sass app.scss : app.css. I tried to configure it using extract-text-webpack-plugin, but I am doing something wrong or missing smth.
It worked if I include(app.scss) in app.js but this makes no sense because if anyone has disabled JavaScript the styles won't work.
This is my webpack.config.js file. I have no idea how to do it.
const webpack = require("webpack");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
var jsConfig = {
entry: "./_dev/scripts/app.js",
output: { filename: "./scripts/bundle.js" },
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
}
]
}
};
var scssConfig = {
entry: "./_dev/scss/app.scss",
output: { filename: "./content/app.css" },
module: {
rules: [
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
}
]
},
plugins: [
new ExtractTextPlugin({filename:"./_dev/scss/app.scss"}),
]
};
var config = [scssConfig, jsConfig];
module.exports = config;
Edit: I also found this. This series would have helped with all my questions so if you have similar questions make sure to read it before asking!
https://codeburst.io/simple-beginner-guide-for-webpack-2-0-from-scratch-part-v-495dba627718
You need to include your app.scss for webpack to be able to find your scss references because webpack will traverse your project and apply loaders to all files it can find through references starting from app.js recursively down. If you don't have references to app.scss somewhere in the project webpack can't find it and it won't build it. So in the entry of you project (assume it is app.js) you need to do this:
import 'relative/path/to/styles/app.scss';
But it doesn't mean that those who don't have js enabled won't receive your styles. You need to include app.scss only for the build phase of your project, after that your styles will be included in html and will be loaded even for those without js enabled.
webpack concepts section explains how webpack finds dependencies based on your entry point building its internal graph of dependencies.
Update:
There is a way that allows you to not add your app.scss in your js. You can include multiple files in your entry object in your webpack config. Here is an example of how configuration might look in your case:
const webpack = require("webpack");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
var config = {
entry: {
main: [
"./_dev/scripts/app.js",
"./_dev/scss/app.scss"
],
},
output: {
path: './scripts',
filename: "bundle.js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
},
{
test: /\.(css|scss)/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: ['css-loader', 'sass-loader']
})
}
]
},
plugins: [
new ExtractTextPlugin("./_dev/scss/app.scss"),
]
};
module.exports = config;
More information available on SO question webpack-multiple-entry-points-sass-and-js.
You also have incorrect configuration of ExtractTextPlugin in webpack. You are placing the whole path in the option for filename, which is not correct. In your case it should look like this:
plugins: [
new ExtractTextPlugin("./_dev/scss/app.css"),
]
I am using the package electron-notifications and it relies on a .html and .css file in its assets folder. This assets folder is not included in webpack (1.14.0) though.
I know I should not add a module as an entry point. I have come across a concept called code splitting, but I'm not clear on how that works and if that is what I need to be looking into further. Any advice you can give would be greatly appreciated.
webpack.config.production.js
import path from 'path';
import webpack from 'webpack';
import validate from 'webpack-validator';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import merge from 'webpack-merge';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import BabiliPlugin from 'babili-webpack-plugin';
import baseConfig from './webpack.config.base';
export default validate(merge(baseConfig, {
devtool: 'inline-source-map',
entry: [
'babel-polyfill',
'./app/index'
],
output: {
path: path.join(__dirname, 'app/dist'),
publicPath: '../dist/'
},
module: {
loaders: [
// Extract all .global.css to style.css as is
{
test: /\.global\.css$/,
// loaders: [
loader: ExtractTextPlugin.extract(
'style-loader',
'css-loader?sourceMap'
)
// ]
},
// Pipe other styles through css modules and append to style.css
{
test: /^((?!\.global).)*\.css$/,
// loaders: [
loader: ExtractTextPlugin.extract(
'style-loader',
'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
)
},
// Fonts
{ test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/font-woff' },
{ test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/font-woff' },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream' },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file' },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml' },
// Images
{
test: /\.(?:ico|gif|png|jpg|jpeg|webp)$/,
loader: 'url-loader'
}
]
},
plugins: [
// https://webpack.github.io/docs/list-of-plugins.html#occurrenceorderplugin
// https://github.com/webpack/webpack/issues/864
new webpack.optimize.OccurrenceOrderPlugin(),
// NODE_ENV should be production so that modules do not perform certain development checks
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
}),
new BabiliPlugin(),
new ExtractTextPlugin('style.css', { allChunks: true }),
new HtmlWebpackPlugin({
filename: '../app.html',
template: 'app/app.html',
inject: false
})
],
// https://github.com/chentsulin/webpack-target-electron-renderer#how-this-module-works
target: 'electron-renderer'
}));
If you want that packages' CSS to be recognised by the webpack, you just add it to the style's(CSS's) loader block, as an include attribute along with "test" and "loader". In the include attribute point it to the node_modules/electron_notification path.
HTML of that package need not be included, since your Single Page Application, has it's own HTML, if needed try to replicate the class names there. But I doubt if you need to do that.
In my project I use Webpack with React and NodeJS. I want to generate a bundle.js and style.css file. Currently I've got the following code:
var webpack = require('webpack')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
module.exports = {
entry: './index.js',
output: {
path: 'public',
filename: 'bundle.js',
publicPath: ''
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015']
}
},
{ test: /\.scss$/, loader: ExtractTextPlugin.extract('css!sass') }
]
},
plugins: [
new ExtractTextPlugin('public/style.css')
]
}
But when I run webpack only the JS file is created in the ./public map:
Asset Size Chunks Chunk Names
bundle.js 844 kB 0 [emitted] main
+ 222 hidden modules
Following examples/tutorials it's only oriented on CSS files, or obvious mistakes where made like not implementing ExtractText.
I've also downloaded the packages sass-loader node-sass. In some examples I did found those packages where included, in some they weren't.
EDIT (require style in index.js):
import React from 'react'
import { render } from 'react-dom'
import { Router, browserHistory } from 'react-router'
import routes from './modules/routes'
require('./public/style.css')
render(
<Router routes={routes} history={browserHistory} />,
document.getElementById('app')
)
EDIT (webpack.config.js):
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015']
}
},
{
test : /\.scss$/,
include : path.join(__dirname, './public/sass'),
loaders : ["style", "css", "sass"]
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('css!sass')
}
]
},
sassLoader: {
includePaths: [path.join(__dirname, './public/sass')]
},
plugins: [
new ExtractTextPlugin(path.join(__dirname, './public/style.css'))
]
My folder structure looks like this:
webpack.config.js
index.js
/public
index.html
bundle.js (generated)
/sass
style.scss
basics.scss (imported in style.scss)
Make sure that you require your style file.
e.g.
require('../sass/app.scss');
and I think you need style loader as well
e.g.
{
test : /\.scss$/,
include : path.join(__dirname, 'sass'),
loaders : ["style", "css", "sass"]
}
These three loaders perform following operations
Turn your scss files into plain CSS with the sass loader
Resolve all the imports and url(...)s in the CSS with the help of CSS loader
Insert those styles into the page with the style loader
You need a combination of the ExtractTextPlugin and the style loader.
module: {
loaders: [
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader!sass-loader'),
},
],
}
...
plugins: [
new ExtractTextPlugin(path.join(__dirname, 'public', 'style.css')),
],
In my working configs, I also have a possibly extraneous entry in resolve:
resolve: {
loaders: [
{
test: /\.(css|scss)$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader'),
},
],
},
The other error might be how you're including it in index.js. You're using require('./public/style.css') rather than require('./public/style.scss').