Information: I do not use NextJS in this project.
When I start my devSever I have a problem with styled-jsx/webpack as I mentioned in the title. When I try to add a new rule to CSS about scoped styled I get an error styled-jsx/css: if you are getting this error it means that yourcsstagged template literals were not transpiled.
I tried to fix my config with these topics:
https://github.com/zeit/styled-jsx/issues/537
https://github.com/zeit/styled-jsx/issues/498
https://github.com/zeit/styled-jsx/issues/469#issuecomment-423243758
https://github.com/zeit/styled-jsx/issues/434#issuecomment-415801021
but It doesn't work in my case and I don't know what I'm doing wrong.
My webpack config:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ni = require('os').networkInterfaces();
const host = Object.keys(ni)
.map(interf => ni[interf].map(o => !o.internal && o.family === 'IPv4' && o.address))
.reduce((a, b) => a.concat(b))
.filter(o => o)[0];
const config = {
mode: 'development',
entry: './docs/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: '/'
},
resolve: {
alias: {
myPackage: path.resolve('./src/index')
}
},
module: {
rules: [
{
test: /\.css$/i,
use: [
{
loader: require('styled-jsx/webpack').loader,
options: {
type: 'scoped'
}
}
]
},
{
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader']
},
{
test: /\.css$/i,
exclude: /\.module\.css$/i,
use: ['style-loader', 'css-loader']
},
{
test: /\.module\.css$/i,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true
}
}
]
},
{
test: /\.(scss)$/,
use: ['css-loader', 'sass-loader']
},
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader' },
{ test: /\.(woff|woff2)$/, loader: 'url-loader?prefix=font/&limit=5000' },
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url-loader?limit=10000&mimetype=application/octet-stream'
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
issuer: {
test: /\.jsx?$/
},
use: ['babel-loader', '#svgr/webpack', 'url-loader']
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url-loader'
},
{
test: /\.png(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url-loader?limit=10000&mimetype=image/png'
},
{
test: /\.gif(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url-loader?limit=10000&mimetype=image/gif'
}
]
},
devServer: {
historyApiFallback: true,
open: true,
compress: true,
port: 8080,
host,
hot: true
},
plugins: [
new HtmlWebpackPlugin({
template: 'public/index.html'
})
]
};
module.exports = config;
I tried also to add this styled-jsx/webpack loader in the same rules with babel-loader ( with style-loader and css-loader too) but It doesn't work either. Like this:
{
test: /\.(js?|css)$/,
// exclude: /node_modules/,
use: [
{
// I tried put a style-lodaer and css-lodaer to this rule but It dosent'work
loader: require('styled-jsx/webpack').loader,
options: {
type: 'scoped'
}
},
'babel-loader'
]
},
.babelrc
{
"presets": ["#babel/env", "#babel/preset-react"],
"plugins": [
"#babel/proposal-class-properties",
[
"styled-jsx/babel",
{
"optimizeForSpeed": true
}
]
]
}
I want to have a scoped css styles when import styles from css like a object and put them to the {styles}.
Do you have any advice about what I should do?
Related
I am trying to reduce the size of my build file ( main.js ) to 500kb or less.
Initially it was 1.2MB and with some code splitting and webpack I managed to reduce it to around 600kb but I need to reduce it by another 100kb.
I am fairly new to webpack and I would appreciate any feedback.
Bellow you can find my webpack.prodduction.config.js
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const webpack = require('webpack')
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin')
console.log(`Building for: ${process.env.NODE_ENV}`)
module.exports = {
module: {
rules: [
{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/
}, {
test: /\.css$/,
loader: 'style-loader!css-loader'
}, {
test: /\.(jpe?g|png|gif|woff|woff2|eot|ttf|svg)(\?[a-z0-9=.]+)?$/,
loader: 'url-loader?limit=100000' },
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
options: {
presets: [
['#babel/preset-env', {
useBuiltIns: false,
modules: false
}]
],
plugins: [
'#babel/plugin-transform-runtime',
'#babel/plugin-proposal-class-properties',
'inline-react-svg'
]
},
loader: 'babel-loader'
}
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.module\.s(a|c)ss$/,
loader: [
{
loader: 'style-loader',
options: {
attrs: { class: 'BasebotTag' }
}
},
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[name]__[local]___[hash:base64:5]',
camelCase: true
}
},
{
loader: 'sass-loader'
}
]
},
{
test: /\.(woff(2)?|ttf|eot|svg|otf)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/'
}
}
]
},
{
test: /\.s(a|c)ss$/,
exclude: /\.module.(s(a|c)ss)$/,
loader: [
{
loader: 'style-loader',
options: {
attrs: { class: 'BasebotTag' }
}
},
'css-loader',
{
loader: 'sass-loader'
}
]
}
]
},
resolve: {
extensions: ['.js', '.jsx', '.scss']
},
plugins: [
new UglifyJSPlugin(),
new LodashModuleReplacementPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
}),
new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en/),
new webpack.optimize.ModuleConcatenationPlugin(),
new MiniCssExtractPlugin({
filename: '[name].[hash].css',
chunkFilename: '[id].[hash].css'
}),
new LodashModuleReplacementPlugin({
caching: true,
cloning: true
})
]
}
EDIT:
This is my build script:
"build": "NODE_ENV=production webpack --config webpack.production.config",
You are inlining images and other assets up to 0.1MB (100000 Bytes) with url-loader. It would not take many assets with a size of this upper limit to increase your bundle size significantly. In fact, reducing this limit and un-inlining just one asset of 100KB would mean you meet your target bundle size.
I would suggest only inlining assets that are less than 10KB (10000 Bytes). Everything larger than this can be fetched with an HTTP request when it is needed.
{
test: /\.(jpe?g|png|gif|woff|woff2|eot|ttf|svg)(\?[a-z0-9=.]+)?$/,
loader: 'url-loader?limit=10000' }, // <= lower the limit here to 10000
}
Everything was working fine. I installed npm module simplewebrtc and it stopped working.
The error I get is window is not defined:
webpack:///./node_modules/#andyet/simplewebrtc/node_modules/webrtc-adapter/src/js/adapter_core.js?:16
const adapter = Object(_adapter_factory_js__WEBPACK_IMPORTED_MODULE_0__["adapterFactory"])({window});
^
ReferenceError: window is not defined
at eval (webpack:///./node_modules/#andyet/simplewebrtc/node_modules/webrtc-adapter/src/js/adapter_core.js?:16:93)
at Module../node_modules/#andyet/simplewebrtc/node_modules/webrtc-adapter/src/js/adapter_core.js (/Users/testmac/node/test-frontend/frontend-test/server.js:2505:1)
at __webpack_require__ (/Users/testmac/node/test-frontend/frontend-test/server.js:21:30)
at eval (webpack:///./node_modules/#andyet/simplewebrtc/module.js?:37:72)
at Module../node_modules/#andyet/simplewebrtc/module.js (/Users/testmac/node/test-frontend/frontend-test/server.js:2493:1)
at __webpack_require__ (/Users/testmac/node/test-frontend/frontend-test/server.js:21:30)
at eval (webpack:///./app/src/components/common/calling/CallingSimple.js?:7:78)
at Module../app/src/components/common/calling/CallingSimple.js (/Users/testmac/node/test-frontend/frontend-test/server.js:1500:1)
at __webpack_require__ (/Users/testmac/node/test-frontend/frontend-test/server.js:21:30)
at eval (webpack:///./app/src/routes.js?:36:99)
I applied the solution given in this link but it did not work
My webpack.config.js is as follows:
const webpack = require('webpack')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const ImageminPlugin = require('imagemin-webpack')
const imageminGifsicle = require('imagemin-gifsicle')
const imageminJpegtran = require('imagemin-jpegtran')
const imageminOptipng = require('imagemin-optipng')
const imageminSvgo = require('imagemin-svgo')
const server = {
entry: ['#babel/polyfill', './app/src/server.js'],
target: 'node',
output: {
path: __dirname,
filename: 'server.js',
globalObject: "this"
// libraryTarget: "commonjs2"
},
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: 'dist/assets/images/[name].[ext]'
}
},
{
test: /\.(css)$/,
loader: 'file-loader',
options: {
name: '/dist/assets/css/[name].[ext]'
}
},
// File loader used to load fonts
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
loader: 'file-loader',
options: {
name: '/dist/assets/fonts/[name].[ext]'
}
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader']
})
}
]
},
plugins: [
new ExtractTextPlugin({
filename: 'dist/assets/css/style.bundle.css'
}),
new webpack.BannerPlugin({
banner: '__isBrowser__ = false;',
raw: false,
include: /\.js$/
})
]
}
const client = {
entry: ['#babel/polyfill', './app/src/client.js'],
output: {
path: __dirname,
filename: './dist/app.bundle.js',
globalObject: "this"
},
devtool: 'source-map',
module: {
rules: [{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '/dist/assets/images/[name].[ext]'
}
},
{
test: /\.(css)$/,
loader: 'file-loader',
options: {
name: 'dist/assets/css/[name].[ext]'
}
},
// File loader used to load fonts
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
loader: 'file-loader',
options: {
name: '/dist/assets/fonts/[name].[ext]'
}
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader']
})
},
{
test: /js$/,
exclude: /(node_modules)/,
loader: 'babel-loader'
}
]
},
plugins: [
new ExtractTextPlugin({
filename: 'dist/assets/css/style.bundle.css'
}),
new OptimizeCssAssetsPlugin(),
new BundleAnalyzerPlugin(),
new ImageminPlugin({
bail: false,
cache: true,
imageminOptions: {
plugins: [
imageminGifsicle({
interlaced: true
}),
imageminJpegtran({
progressive: true
}),
imageminOptipng({
optimizationLevel: 5
}),
imageminSvgo({
removeViewBox: true
})
]
}
})
]
}
module.exports = (env) => [server, client]
But the error is still there.
When I try to use command npm start, I get error
"] Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema."
Code: https://next.plnkr.co/edit/hEHTiPYQXQ7POWIH?open=lib%2Fscript.js&deferRun=1
Here is my full configuration code for webpack
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/app/app.js',
output: {
path: './dist',
filename: 'app.bundle.js',
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
{
test: /\.html$/,
use: 'raw-loader'
},
{
test: /\.scss$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader'
},
{
loader: 'sass-loader',
}
]
},
{
test: /\.css$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader'
}
]
},
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.html',
inject: 'body',
hash: true
}),
],
devtool: "#inline-source-map"
}
Error:
Did not detect a `bs-config.json` or `bs-config.js` override file. Using lite-server defaults...
[0] ** browser-sync config **
[0] { injectChanges: false,
[0] files: [ './**/*.{html,htm,css,js}' ],
[0] watchOptions: { ignored: 'node_modules' },
[0] server: { baseDir: './', middleware: [ [Function], [Function] ] } }
] Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
[1] - configuration.module has an unknown property 'loaders'. These properties are valid:
[1] object { defaultRules?, exprContextCritical?, exprContextRecursive?, exprContextRegExp?, exprContextRequest?, noParse?, rules?, strictExportPresence?, strictThisContextOnImports?, unknownContextCritical?, unknownContextRecursive?, unknownContextRegExp?, unknownContextRequest?, unsafeCache?, wrappedContextCritical?, wrappedContextRecursive?, wrappedContextRegExp? }
[1] -> Options affecting the normal modules (`NormalModuleFactory`).
[1] - configuration.output.path: The provided value "./dist" is not an absolute path!
[1] -> The output directory as **absolute path** (required).
I found your problem webpack use rules config not loader config so change your code into this
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require("path");
module.exports = {
entry: 'src/app/app.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index_bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
{
test: /\.html$/,
use: 'raw-loader'
},
{
test: /\.scss$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader'
},
{
loader: 'sass-loader',
}
]
},
{
test: /\.css$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader'
}
]
},
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'index.html',
inject: 'body',
hash: true
}),
],
devtool: "#inline-source-map"
}
Update: move your index.html file into same level of webpack.config.js
I dont see in the document they allow user to change into different path
Please let me know if you still have a problem
I'm trying to configure my webpack to use css modules for all the scss files except for the files in the "src/scss" and "node_modules" folder. Below are my configuration file
const webpack = require('webpack');
const combineLoaders = require('webpack-combine-loaders');
const ImageMinPlugin = require('imagemin-webpack-plugin').default;
const HtmlWebpackPlugin = require('html-webpack-plugin');
const WebappWebpackPlugin = require('webapp-webpack-plugin');
const path = require('path');
const NODE_ENV = process.env.NODE_ENV || 'development';
const DEV_MODE = NODE_ENV !== 'production';
const PORT = process.env.PORT || 3000;
const FAVICON_DIR = './src/assets/favicon/favicon.png';
const ENTRY_CSS = path.resolve(__dirname, 'src/scss');
const NODE_MODULE_PATH = path.resolve(__dirname, 'node_modules')
console.log('ENTRY_CSS: ', ENTRY_CSS);
console.log('NODE_MODULE_PATH: ', NODE_MODULE_PATH);
const styleRules = () => [
{
test: /\.scss$/,
exclude: [
ENTRY_CSS,
NODE_MODULE_PATH
],
loader: combineLoaders([
{
loader: 'style-loader',
},
{
loader: 'css-loader',
query: {
modules: true,
importLoaders: 1,
localIdentName: '[local]--[hash:base64:5]',
},
},
{
loader: 'postcss-loader',
options: {
plugins: function () {
return [
require('precss'),
require('autoprefixer')
];
}
}
},
{
loader: 'sass-loader',
query: {
includePaths: ['./src'],
},
},
]),
},
{
test: /\.css$/,
include: [
path.resolve(__dirname, 'src')
],
loader: combineLoaders([
{
loader: 'style-loader',
},
{
loader: 'css-loader',
query: {
modules: true,
importLoaders: 1,
localIdentName: '[local]--[hash:base64:5]',
},
},
]),
},
/**
* for global style, import libs, no CSS module applied for those files imported here.
*/
{
test: /\.scss$/,
include: [
ENTRY_CSS,
NODE_MODULE_PATH
],
loader: combineLoaders([
{
loader: 'style-loader',
},
{
loader: 'css-loader',
query: {
modules: false,
},
},
{
loader: 'postcss-loader',
options: {
plugins: function () {
return [
require('precss'),
require('autoprefixer')
];
}
}
},
{
loader: 'sass-loader',
query: {
includePaths: ['./src'],
},
},
]),
},
];
module.exports = {
entry: ['./src/index.tsx'],
mode: DEV_MODE ? 'development' : 'production',
devtool: DEV_MODE ? 'source-map' : '',
module: {
rules: [
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader'
},
{
loader: 'ts-loader',
options: {
configFile: DEV_MODE ? 'tsconfig.json' : 'tsconfig.deploy.json',
},
},
],
},
...styleRules(),
{
test: /\.(png|jpe?g|gif|svg)$/,
use: [
{
loader: 'file-loader',
options: {},
},
],
},
{
test: /\.(ttf|eot|woff)(\?v=[0-9].[0-9].[0-9])?$/,
use: [
{
loader: 'file-loader',
options: {},
},
],
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js', '.json'],
},
output: {
path: __dirname + '/dist',
publicPath: '/',
filename: 'bundle.[hash].js',
},
devServer: {
contentBase: './dist',
compress: true,
port: PORT,
historyApiFallback: true,
open: true,
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(NODE_ENV),
'process.env.PORT': JSON.stringify(PORT),
}),
new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html',
}),
...(FAVICON_DIR ? [new WebappWebpackPlugin(FAVICON_DIR)] : []),
new ImageMinPlugin({
disable: DEV_MODE,
pngquant: {
quality: '95-100',
},
test: /\.(jpe?g|png|gif|svg)$/i,
}),
],
};
I'm importing Bootstrap's SCSS files in "main.scss" which is place inside the "src/scss" folder. The bootstrap files are also being hashed by css modules when I run my app. Can I know what mistake am I doing?
You can use exclude option of css-loader,
loaders: [{
test: /\.scss$/,
exclude: fs.realpathSync('./node_modules/path/to/bootstrap/src/styles')
loader: cssModulesLoader,
}
I have the following webpack file, however, when I run npm run dev the name.bundle.css file doesn't get generated: (no errors either)
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
context: path.resolve(__dirname, './resources/'),
entry: {
app: './index.jsx'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, './public/assets/'),
publicPath: '/assets/'
},
module: {
rules: [
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
use: [{
loader: 'css-loader'
}],
}),
},
{
test: /\.jsx|js$/,
exclude: [/node-modules/],
use: [
{
loader: "babel-loader",
options: { presets: ['react', 'es2015', 'stage-1'] }
}
]
},
{
test: /\.(sass|scss)$/,
use: ["style-loader", "css-loader", "sass-loader"]
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
use: ['file-loader?name=[name].[ext]']
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
loader: 'file-loader?name=public/fonts/[name].[ext]'
}
]
},
resolve: {
modules: [
path.resolve(__dirname, './resources/'),
'node_modules'
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'common'
}),
new ExtractTextPlugin({
filename: '[name].bundle.css'
})
]
}
my CSS folder is:
CSS
- app.scss
COMPONENTS
comp1.scss
comp2.scss
it works this way "import styles from './css/app.scss';" but I would expect this to generate a app.bundle.css:
new ExtractTextPlugin({
filename: '[name].bundle.css'
})
You have 2 rules for both css and sass.
I think in your case you only need one:
test: /\.(sass|scss)$/,
use: ExtractTextPlugin.extract({
use: [{
loader: "css-loader"
}, {
loader: "sass-loader"
}],
fallback: "style-loader"
})
and like you said, you should import the scss files in the js files import './css/app.scss'