Cant use css modules in React with Bootstrap4 - reactjs

I want to use React CSS modules with Bootstrap.
First, I created a project with the create-react-app command. Then, I installed Bootstrap 4 with NPM and included it in my app.js like:
import 'bootstrap/dist/css/bootstrap.css';
I also did npm eject to have access to my Webpack config file.
Meanwhile I wanted to use CSS modules in my layout.js file, so I went to webpack.config.dev.js and changed modules to true:
test: /\.css$/,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
modules: true
}
When I change modules to true Bootstrap CSS is not showing correctly. If I change modules to false then Bootstrap is working. Any idea?
Modules: true
Modules: false

Here's a good discussion how to use CSS-modules with other global CSS (e.g. Bootstrap)
https://github.com/css-modules/css-modules/pull/65
Hope it helps.
I had same issue and just loaded bootstrap directly in the index.html from public folder. My project not so big to include bootstrap in the same bundle
P.S.
Actually, I also tried this solution and it works good for me.
https://github.com/css-modules/css-modules/issues/113
I just renamed all of my global css files as .global..css
{
test: /^((?!\.global).)*\.css$/, // anything with .global will not
go through css modules loader
loaders: [
'style-loader',
'css-loader?modules&sourceMap&importLoaders=1&localIdentName=
[name]__[local]___[hash:base64:5]',
'postcss-loader'
]
}

Related

How can I use absolute paths in my React styleguidist component library?

I have a React component library that is used in a React app. The component library is setup using Styleguidist and webpack. I've setup webpack to use absolute paths using:
webpackConfig: {
resolve: {
modules: [path.resolve(__dirname, 'src/'), 'node_modules'],
}
}
This works within the context of the component library. When I build the component library, the package looks like this:
/core
/components
/Table
/Row
When I import the components into my app, I get an error:
Module not found: Can't resolve components/Row in /Users/myusername/Sites/mysite/node_modules/#mypackage/core/components/Table
I understand why the paths don't match in the context of node_modules, but I would've expected Webpack to transform those import paths during the build process. Is there something I'm missing? Or is this not possible?
While Styleguidist uses webpack, it turns out the build script we were using does not, so the webpack config is irrelevant. Instead, our build script (https://www.npmjs.com/package/cod-scripts) uses babel.
We ended up having to add a separate babel.config.js file to define absolute paths for babel using the babel-plugin-module-resolver package.
npm install babel-plugin-module-resolver --saveDev
npm install #babel/preset-react --saveDev
babel.config.js
module.exports = {
plugins: [
[
'module-resolver',
{
root: ['./src'],
},
],
],
presets: ['#babel/preset-react'],
};

React images won't load even with require suntax

I am building a project but i am facing an issue where React doesn’t load the images even with the require syntax <img src={require('./images/Jonas.jpg')} alt="test" />
It works perfectly fine when i import the image import image from './images/Jonas.jpg' but for some reason it is not working with require which is absolutely crucial for the project...
Any ideas what might be the problem here ? Thanks in advance
You can use file-loader for this
Follow these steps
npm install file-loader --save-dev
Then add the loader to your webpack config.
webpack.config.js
{
test: /\.(jpg|png|svg|gif)$/,
loader: 'file-loader',
options: {
name: '[path][name].[ext]'
}
},

Using Webpack on an existing angular 1.x application

I have an existing, very large, angular 1.x application which runs today ES5 code.
Almost all of the application runs on the same module. My main module is defined in the file "dashboardApp.js".
I want to start using ES6 with modules per component as the app is component structured. For it to run in develpment, I want to start using Webpack.
I tried adding Webpack so I added all the needed npm dependencies and added the following webpack.config.js
var webpack = require('webpack');
module.exports = {
entry: '../app/dashboardApp.js',
output:{
path: __dirname + '/../dst/dist',
filename: 'my.bundle.js'
},
module:{
rules: [{
test: /\.js$/,
loader: 'babel-loader',
exclude: /(node_modules|bower_components)/
}]
}
};
Also, I added to package.json the following property:
"scripts": {
"build": "webpack --config webpack.config.js"
},
and was able to successfully run build and create my.bundle.js. However, when trying to load the app using just the my.bundle.js script, I got an exception:
Uncaught Error: [$injector:modulerr] Failed to instantiate module dashboardApp due to:
Error: [$injector:unpr] Unknown provider: myConsts
myConsts is an angular constant which was included before using Webpack by loading the script and hence my question:
Whats needed in order to transform an existing angular 1.x app that used to load all scripts explicitly to be one Webpack generated script app. What changes I need to do in all my files, that are all defined on the same module, in order to be included in the generated file. I understand that webpack is a module bundler, but I lack the understanding on what I need to do in order to make the old app work with Webpack. Do I need to transform all the files to ES6 module import/export syntax? How does Webpack knows what files to load when the old angular syntax (1 controller/service/constant... per file when all on the same module)? What does it do given the entry point.
Thanks
If your app is using requirejs, then you could achieve it using webpack2. Just configure it properly using rules and aliases. My app too uses requirejs and I successfully managed to replace Grunt with webpack2 after a lot of struggle.
Below is the webpack.config.js file:
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
let basePath = path.join(__dirname, '/');
let config = {
// Entry, file to be bundled
entry: {
'main': basePath + '/src/main.js',
},
devtool: 'source-map',
output: {
// Output directory
path: basePath + '/dist/',
library: '[name]',
// [hash:6] with add a SHA based on file changes if the env is build
filename: env === EnvEnum.BUILD ? '[name]-[hash:6].min.js' : '[name].min.js',
libraryTarget: 'amd',
umdNamedDefine: true
},
module: {
rules: [{
test: /(\.js)$/,
exclude: /(node_modules|bower_components)/,
use: {
// babel-loader to convert ES6 code to ES5 + amdCleaning requirejs code into simple JS code, taking care of modules to load as desired
loader: 'babel-loader',
options: {
presets: ['es2015'],
plugins: []
}
}
}, { test: /jQuery/, loader: 'expose-loader?$' },
{ test: /application/, loader: 'expose-loader?application' },
{ test: /base64/, loader: 'exports-loader?Base64' }
]
},
resolve: {
alias: {
'jQuery': 'bower_components/jquery/dist/jquery.min',
'application': 'main',
'base64': 'vendor/base64'
},
modules: [
// Files path which will be referenced while bundling
'src/**/*.js',
'src/bower_components',
path.resolve('./src')
],
extensions: ['.js'] // File types
},
plugins: [
]
};
module.exports = config;
Let me know if you have any more queries. I still remember how hard I had to try to make things work. WIll be happy to help you!
Putting this here in case anyone else runs into this problem. Essentially what webpack is trying to do is build a dependency graph. Meaning there is an entry point, and then webpack will look at that file and see what it depends on by seeing if there are any imports or require statements in it. It will then travel to the dependency file and bundle that while also looking for more dependencies and so on. In this way, it knows what things need to be loaded before others.
It sounds like you didn't alter your source code to import or require any of the module's dependencies, so Webpack simply built that one file you pointed it to instead of all of the files of your app.
Lets say ModuleA depends on ModuleB and ModuleC.
in ModuleA.js, you'll import (or require) moduleB as well as ModuleC.
In both ModuleB and ModuleC, you'll need to export them and make sure your exporting the .name property from the module since AngularJS wants strings for its dependencies.
The tricky thing about using AngularJS with Webpack, is that Angular has its own Module system which is different from the commonJS pattern or ESModules, so its a bit of an odd combination.
Softvar's solution above works because he told webpack what to bundle when defining his modules under the resolve property. If all of your sub modules are exported, another solution to bundling all of your angular files into one parent module to export, is like this, where the file is index.js and webpack looks here as its entry point:
const modules = [];
function importAll(webpackContext) {
// the webpackContext parameter is a function returned after invoking require.context() that has
// access to all of the resolved paths defined in the require.context call.
// The keys will be an array of all of the resolved module paths returned from the initial
// require.context invocation within the importAll invocation a number of lines below this declaration.
webpackContext.keys()
// this will fetch each module itself and give us access to all of the exports from that module.
// Since we are exporting the angular modules as the default export from all of our index files,
// we are just pushing the default property into the modules array. In this case the default property
// is the string name of the angular module.
.forEach(modulePath => modules.push( webpackContext(modulePath).default) );
}
// recurse through all sub directories in ./src and find the path for each index.js file.
importAll(require.context("./src/", true, /index\.js$/));
// take all of the module's name strings and spread them out as module dependencies.
// export the single module all glued together.
export default angular.module("YOUR_MODULE_NAME", [...modules]).name;

using webpack ProvidePlugin in React storybook custom webpack config

I've built a wrapper package for drag and drop in React, and I added storybook examples.
Since in my consumer React is exposed globally, i'm not importing React explicitly.
In the storybook examples I need to supply React as part of the custom webpack config, but for some reason it can't resolve React and I get a ReferenceError: React is not defined
This is the package - https://github.com/fiverr/drag_n_drop_package
And this is the custom webpack config file:
const webpack = require('webpack');
module.exports = {
plugins: [
new webpack.ProvidePlugin({
React: 'react'
})
],
module: {
loaders: [
{
test: /\.scss$/,
loader: 'style!raw!sass'
}
]
}
};
This is really strange but your storybook webpack.config.js is mixing webpack v1/v2.
Importing webpack as
const webpack = require('#kadira/storybook/node_modules/webpack');
solves it because it uses the same webpack reference that storybook is using (v1).
I found the following code in webpack.config.js at github:
externals: {
react: 'React'
}
It looks as this question. If it needs to load the React lib from external, like CDN. The page has to be sure have a script tag for importing React lib. And make sure this script tag is in front of the bundle.js or the file which it generated by webpack, so the Object of React will exist when the following code needs to use React, such as:
<script src="./react.js"></script>
<script src="./bundle.js"></script>

Using a text loader in Webpack for RequireJS text plugin

So my AngularJS code looks like this:
define(['angular', 'text!./template.html'], function (angular, template) {
'use strict';
return angular.module('app.widget', [])
.directive('MyWidget', function(){
//.... use the template here
})
I'm using the text plugin for RequireJS to get the html template and use in in the AngularJS directive.
I want to use webpack and it's reading the AMD style code ok but it can't work with the text plugin.
Does anyone know how to get the text-loader for webpack to work with requirejs?
There are some solutions out there and a discussion thread but I can't get them to work.
In my webpack.config.js I've got
loaders: [
{ test: /^text\!/, loader: "text" }
]
Thanks
Actually you need dont need to specify node modules path. It works if you specify just the name of the actual loader like below
resolveLoader: {
alias: { "text": "text-loader" }
},
You need to install raw-loader, which is the webpack equivalent for loading raw files
npm i raw-loader
Then you need to alias the requireJS style with the raw-loader (resolveLoader is to be put in the root of the webpack config object)
resolveLoader: {
alias: {
'text': {
test: /\.html$/,
loader: "raw-loader"
},
}
}
Check this SO question: Webpack loader aliases?
A similar solution which worked for me with Webpack 2.2:
resolveLoader: {
alias: {
// Support for require('text!file.json').
'text': 'full/path/to/node_modules/text-loader'
}
}
And install text-loader:
npm install text-loader

Resources