css modules object import returns empty - reactjs

I am trying to use css modules inside react, but it is not working.
The log of this code:
import React from 'react'
import styles from '../../css/test.css'
class Test extends React.Component {
render() {
console.log(styles)
return (
<div className={styles.app}>
<p>This text will be blue</p>
</div>
);
}
}
export default Test
returns Object {}
and the rendered code are tags with no class:
<div><p>This text will be blue</p></div>
The css code is available at site, here is my test.css:
.test p {
color: blue;
}
If I changed the div to have class='test', the color of p changes to blue
Here is my webpack.config.js
var path = require('path')
var webpack = require('webpack')
var HappyPack = require('happypack')
var BundleTracker = require('webpack-bundle-tracker')
var path = require('path')
var ExtractTextPlugin = require("extract-text-webpack-plugin")
function _path(p) {
return path.join(__dirname, p);
}
module.exports = {
context: __dirname,
entry: [
'./assets/js/index'
],
output: {
path: path.resolve('./assets/bundles/'),
filename: '[name].js'
},
devtool: 'inline-eval-cheap-source-map',
plugins: [
new BundleTracker({filename: './webpack-stats.json'}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
}),
new HappyPack({
id: 'jsx',
threads: 4,
loaders: ["babel-loader"]
}),
new ExtractTextPlugin("[name].css", { allChunks: true })
],
module: {
loaders: [
{
test: /\.css$/,
include: path.resolve(__dirname, './assets/css/'),
loader: ExtractTextPlugin.extract("style-loader", "css-loader!resolve-url-loader?modules=true&localIdentName=[name]__[local]___[hash:base64:5]")
},
{
test: /\.scss$/,
include: path.resolve(__dirname, './assets/css/'),
loader: ExtractTextPlugin.extract("style-loader", "css-loader!resolve-url-loader!sass-loader?modules=true&localIdentName=[name]__[local]___[hash:base64:5]")
},
{
test: /\.jsx?$/,
include: path.resolve(__dirname, './assets/js/'),
exclude: /node_modules/,
loaders: ["happypack/loader?id=jsx"]
},
{
test: /\.png$/,
loader: 'file-loader',
query: {
name: '/static/img/[name].[ext]'
}
}
]
},
resolve: {
modulesDirectories: ['node_modules'],
extensions: ['', '.js', '.jsx'],
alias: {
'inputmask' : _path('node_modules/jquery-mask-plugin/dist/jquery.mask')
},
}
}
Can anyone help me?
Thanks in advance.

Looks like your passing the css-loader params to the resolve-url-loader:
"css-loader!resolve-url-loader?modules=true&localIdentName=[name]__[local]___[hash:base64:5]"
Should be:
"css-loader?modules=true&localIdentName=[name]__[local]___[hash:base64:5]&importLoaders=1!resolve-url-loader"

A lot of time passed since this question, so my webpack was update many times with another technologies.
This webpack config is working:
...
module.exports = {
entry,
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/'
},
devtool:
process.env.NODE_ENV === 'production' ? 'source-map' : 'inline-source-map',
module: {
rules: [
{
test: /\.jsx?$/,
include: path.resolve(__dirname, './app/view/'),
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.pcss$/,
include: path.resolve(__dirname, './app/view/'),
use: [
{
loader: 'style-loader'
},
{
loader:
'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
},
{
loader: 'postcss-loader',
options: {
plugins: function() {
return [
require('postcss-import'),
require('postcss-mixins'),
require('postcss-cssnext')({
browsers: ['last 2 versions']
}),
require('postcss-nested'),
require('postcss-brand-colors')
];
}
}
}
],
exclude: /node_modules/
},
{
test: /\.(png|svg|jpg|webp)$/,
use: {
loader: 'file-loader'
}
}
]
},
resolve: {
extensions: ['.js', '.jsx'],
modules: [path.resolve(__dirname, 'node_modules')]
},
plugins
};
I guess that there is an issue with older versions at webpack with this line:
'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
Try importLoaders and importLoader
You can see my repo too.

In my specific case, I'm using official utility facebook/create-react-app. You have to run the following command to get access to the webpack configuration:
npm run eject
You will then need to edit config/webpack.config.js and set the css-loader modules option to true.
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules:true <-----
}),

Related

How to import SASS file in React Webpack relative to project's root directory

I want to be able to import a SASS file in a React component relative to the project's root directory, as opposed to having to do it relative to the component.
I want to be able to do the following in the componenet:
import styles from "styles/popup.sass"
as opposed to
import styles from "../../styles/popup.sass"
I used the resolve options in order to be able to do this and it works for other file types (i.e. .js and .png), but it does not work for .sass files. I get the following error:
Cannot find module 'styles/popup.sass'
I'm not sure why this isn't working for SASS files and would really appreciate any help.
Project Structure:
src
- js
- popup
- greeting_componenet.jsx
- styles
- popus.sass
Webpack Config file
var webpack = require("webpack"),
path = require("path"),
fileSystem = require("fs"),
env = require("./utils/env"),
CleanWebpackPlugin = require("clean-webpack-plugin").CleanWebpackPlugin,
CopyWebpackPlugin = require("copy-webpack-plugin"),
HtmlWebpackPlugin = require("html-webpack-plugin"),
WriteFilePlugin = require("write-file-webpack-plugin");
// load the secrets
var alias = {};
var secretsPath = path.join(__dirname, ("secrets." + env.NODE_ENV + ".js"));
var fileExtensions = ["jpg", "jpeg", "png", "gif", "eot", "otf", "svg", "ttf", "woff", "woff2"];
if (fileSystem.existsSync(secretsPath)) {
alias["secrets"] = secretsPath;
}
var options = {
mode: process.env.NODE_ENV || "development",
entry: {
popup: path.join(__dirname, "src", "js", "popup.js"),
options: path.join(__dirname, "src", "js", "options.js"),
background: path.join(__dirname, "src", "js", "background.js")
},
output: {
path: path.join(__dirname, "build"),
filename: "[name].bundle.js"
},
module: {
rules: [
{
test: /\.css$/,
loader: "style-loader!css-loader",
include: [
path.join(__dirname, 'src'),
/node_modules\/(semantic-ui-css)/
],
},
{
test: /\.(scss|sass)$/i,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 1,
modules: {
localIdentName: "[path]___[name]__[local]___[hash:base64:5]",
},
}
},
{
loader: 'postcss-loader',
options: {
plugins: function() {
return [require('autoprefixer')]
}
}
},
'sass-loader'
],
exclude: /node_modules/
},
{
test: new RegExp('\.(' + fileExtensions.join('|') + ')$'),
loader: "file-loader?name=[name].[ext]",
include: [
path.join(__dirname, 'src'),
/node_modules\/(semantic-ui-css)/
],
},
{
test: /\.html$/,
loader: "html-loader",
exclude: /node_modules/
},
{
test: /\.(js|jsx)$/,
loader: "babel-loader",
exclude: /node_modules/
}
]
},
resolve: {
alias: alias,
extensions: fileExtensions.map(extension => ("." + extension)).concat([".jsx", ".js", ".css", ".sass"]),
modules: [
path.resolve(__dirname, 'src'),
'node_modules'
]
},
plugins: [
// clean the build folder
new CleanWebpackPlugin(),
// expose and write the allowed env vars on the compiled bundle
new webpack.EnvironmentPlugin(["NODE_ENV"]),
new CopyWebpackPlugin([{
from: "src/manifest.json",
transform: function (content, path) {
// generates the manifest file using the package.json informations
return Buffer.from(JSON.stringify({
description: process.env.npm_package_description,
version: process.env.npm_package_version,
...JSON.parse(content.toString())
}))
}
}]),
new HtmlWebpackPlugin({
template: path.join(__dirname, "src", "popup.html"),
filename: "popup.html",
chunks: ["popup"]
}),
new HtmlWebpackPlugin({
template: path.join(__dirname, "src", "options.html"),
filename: "options.html",
chunks: ["options"]
}),
new HtmlWebpackPlugin({
template: path.join(__dirname, "src", "background.html"),
filename: "background.html",
chunks: ["background"]
}),
new WriteFilePlugin()
]
};
if (env.NODE_ENV === "development") {
options.devtool = "cheap-module-eval-source-map";
}
module.exports = options;
You need to add aliases for styles.
Something like:
module.exports = {
//...
resolve: {
alias: {
styles: path.resolve(__dirname, 'src/styles/'),
js: path.resolve(__dirname, 'src/js/')
}
}
};

Webpack eveything loads but the worker

I'm trying to use webpack to bundle my react project. All the modules and everything loads perfectly fine after I defined the webpack_public_path variable.
Everything but the worker.
const path = require('path');
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
module.exports = {
mode: "production",
resolve: {
extensions: ["*", ".ts", ".tsx", ".js", ".mjs", ".css", ".ttf"]
},
module: {
rules: [
{
test: /\.worker\.js$/,
use: {
loader: 'worker-loader',
options: {inline: true}
},
},
{
test: /\.mjs$/,
include: /node_modules/,
type: 'javascript/auto'
},
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.ttf$/,
use: ['file-loader']
},
{
test: /\.ts(x?)$/,
exclude: /node_modules/,
use: [
{
loader: "ts-loader"
}
]
}
]
},
plugins: [
new MonacoWebpackPlugin({
languages: ['markdown'],
})
],
entry: './src/index.tsx',
output: {
path: path.resolve(__dirname, 'assets'),
filename: 'graphqlschemaeditor.js'
}
};
This is my webpack.config.js
Does anyone have an idea what I'm doing wrong? Thanks a lot
Have you tried to specify an explicit publicPath?
E.g.
{
loader: 'worker-loader',
options: { publicPath: '/workers/' }
}
This may resolve loading problems.

Webpack throws error about jsx component

I have the following jsx component:
import React, { Component } from 'react';
class App extends Component {
render () {
return (
<div className="app">
<h2>Welcome to React</h2>
</div>
)
}
}
export default App;
and my webpack file:
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
context: path.resolve(__dirname, './src'),
entry: {
app: './index.jsx'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, './dist/assets'),
publicPath: '/assets',
},
devServer: {
contentBase: path.resolve(__dirname, './src')
},
module: {
rules: [
{
test: /\.jsx$/,
exclude: [/node-modules/],
use: [
{
loader: "babel-loader",
options: { presets: ["es2015"] }
}
]
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
use: [{
loader: 'css-loader',
options: { importLoaders: 1 },
}],
}),
},
{
test: /\.(sass|scss)$/,
use: ["style-loader", "css-loader", "sass-loader"]
}
]
},
resolve: {
modules: [
path.resolve(__dirname, './src'),
'node_modules'
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'common'
}),
new ExtractTextPlugin({
filename: '[name].bundle.css',
allChunks: true
})
]
}
however when I run:
node_modules/.bin/webpack -d
I get the following error:
Add "babel-preset-react"
npm install babel-preset-react
and add "presets" option to babel-loader in your webpack.config.js
Here is an example webpack.config.js:
module: {
loaders: [{
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['react', 'es2015', 'stage-1']
}
}]
}

Code Splitting ~ ReferenceError: System is not defined

My code hit the error
ReferenceError: System is not defined
In line
<IndexRoute getComponent={(nextState, cb) => System.import('./containers/Home').then(module => cb(null, module))} />
How do I define System. Is it related to my webpack settings? Here how I put it
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var stylus = require('stylus');
module.exports = {
debug: true,
devtool: 'eval',
entry: {
"vendor": ["react", "react-router", 'react-dom'],
"app": ['webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './app/App.js']
},
output: {
pathinfo: true,
path: path.resolve(__dirname, 'public'),
filename: '[name].js',
publicPath: 'http://localhost:3000/'
},
plugins: [
new HtmlWebpackPlugin({
title: 'Welcome!',
template: './index_template.ejs',
inject: 'body'
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.optimize.UglifyJsPlugin({
output: {
comments: false
},
compress: {
warnings: false
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: Infinity,
filename: 'vendor.bundle.js'
})
],
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
loaders: ['react-hot', 'babel']
},
{
test: /\.styl$/,
exclude: /(node_modules|bower_components)/,
// loader: 'style!css?resolve url?sourceMap&modules&importLoaders=1&localIdentName=[name]__[local]__[hash:base64:5]!postcss!stylus-loader'
loader: 'style!css?sourceMap&modules&importLoaders=1&localIdentName=[name]__[local]__[hash:base64:5]!postcss!stylus-loader'
},
{
test: /\.(png|jpg)$/,
exclude: /(node_modules|bower_components)/,
loader: 'url-loader?name=images/[name].[ext]&limit=8192'
},
{
test: /\.(ttf|otf|eot)$/,
exclude: /(node_modules|bower_components)/,
loader: 'url-loader?name=fonts/[name].[ext]&limit=8192'
},
{
test: /\.css$/,
loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
},
{
test: /\.scss$/,
loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss!sass?resolve url'
},
{
test: /\.json$/,
loader: 'json-loader'
},
{
test: /\.js$/,
include: path.resolve('node_modules/mapbox-gl-shaders/index.js'),
loader: 'transform/cacheable?brfs'
}
]
},
resolve: {
root: path.join(__dirname, '..', 'app'),
alias: {
'react': path.join(__dirname, 'node_modules', 'react')
},
extensions: ['', '.js', '.jsx', '.json', '.css', '.styl', '.png', '.jpg', '.jpeg', '.gif']
},
stylus: {
'resolve url': true
},
postcss: function () {
return [autoprefixer];
}
};
(Disclaimer: I am new to React-Router and webpack, so this may be
obvious to someone with more familiarity)
Your webpack build stack probably doesn't have configured System.import. I suppose that you use webpack 1 and support of System.import will be only in webpack 2.
You can change your existing code to current popular code splitting solution:
<IndexRoute
getComponent={(nextState, cb) => {
require.ensure([], require => {
// default import is not supported in CommonJS standard
cb(null, require('./containers/Home').default)
});
}}
/>
Note that you must specify .default if you want to use default import in CommonJS standard.

Using react-infinite-calendar with css-modules

I'd like to use react-infinite-calendar component for a personal project. It's not picking up the css. I think my webpack configuration is the problem as I'm using react-css-modules.
Could someone show me what I'd need to do to get it working?
My webpack configuration is:
const CopyWebpackPlugin = require('copy-webpack-plugin');
const path = require('path');
module.exports = {
entry: './index.js',
context: path.join(__dirname, 'client'),
devtool: 'source-map',
output: {
path: './dist/client/',
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.json$/,
loader: 'json-loader'
},
{
// https://github.com/gajus/react-css-modules
test: /\.css$/,
loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
}
]
},
resolve: {
extensions: ['', '.js', '.json']
},
plugins: [
new CopyWebpackPlugin([
{from: 'static/index.html'}
])
]
};
My date selector component is:
import React from 'react';
import InfiniteCalendar from 'react-infinite-calendar';
import 'react-infinite-calendar/styles.css'; // only needs to be imported once
import {TODAY} from '../../server/constants/date';
export default class DateSelector extends React.Component {
render() {
return (
<div>
<InfiniteCalendar
width={400}
height={600}
selectedDate={TODAY}
maxDate={TODAY}
/>
</div>
);
}
}
Another option is to exclude react-infinite-calendar from your CSS module loader and include it in the standard CSS loader.
That way you don't have to rename all of your CSS files.
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.css$/,
exclude: /react-infinite-calendar/,
loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
},
{
test: /\.css$/,
include: /react-infinite-calendar/,
loader: 'style-loader!css-loader',
},
]
I worked around this by having to separate webpack loaders for locally scoped css-modules and globally scoped ones. My webpack configuration is below and so for css modules I've had to name the files so they end with .module.css.
const CopyWebpackPlugin = require('copy-webpack-plugin');
const path = require('path');
module.exports = {
entry: './index.js',
context: path.join(__dirname, 'client'),
devtool: 'source-map',
output: {
path: './dist/client/',
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.json$/,
loader: 'json-loader'
},
{
// https://github.com/gajus/react-css-modules
test: /\.module.css$/,
loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
},
{
test: /^((?!\.module).)*css$/,
loader: 'style-loader!css-loader'
},
]
},
resolve: {
extensions: ['', '.js', '.json']
},
plugins: [
new CopyWebpackPlugin([
{from: 'static/index.html'}
])
]
};

Resources