How to import CSS file on Isomorphic React - Webpack - reactjs

I'm trying to create an isomorphic react app using express, react, and webpack.
Everything works fine until I import a css file in one of my components. I understand node can not handle this import, but can someone explain how this package on github allows their components to have a css import line?
https://github.com/kriasoft/react-starter-kit
I would like to make my project similar to that. Do they have a line anywhere that has the server ignore that line when rendering components?
This is the error I get
SyntaxError: /home/USER/Code/shared/general/ru/src/components/MainPage/MainPage.scss: Unexpected token (1:1)
> 1 | #import '../variables.scss';
| ^
2 |
3 | .MainPage {
4 | background-color: $primary-color;
at Parser.pp.raise (/home/USER/Code/shared/general/ru/node_modules/babylon/lib/parser/location.js:24:13)
at Parser.pp.unexpected (/home/USER/Code/shared/general/ru/node_modules/babylon/lib/parser/util.js:82:8)
at Parser.pp.parseExprAtom (/home/USER/Code/shared/general/ru/node_modules/babylon/lib/parser/expression.js:425:12)
at Parser.parseExprAtom (/home/USER/Code/shared/general/ru/node_modules/babylon/lib/plugins/jsx/index.js:412:22)
at Parser.pp.parseExprSubscripts (/home/USER/Code/shared/general/ru/node_modules/babylon/lib/parser/expression.js:236:19)
at Parser.pp.parseMaybeUnary (/home/USER/Code/shared/general/ru/node_modules/babylon/lib/parser/expression.js:217:19)

You need yet another loader to make css/style loaders to work.
https://www.npmjs.com/package/webpack-isomorphic-tools
But Webpack is made for client side code development only: it finds all require() calls inside your code and replaces them with various kinds of magic to make the things work. If you try to run the same source code outside of Webpack - for example, on a Node.js server - you'll get a ton of SyntaxErrors with Unexpected tokens. That's because on a Node.js server there's no Webpack require() magic happening and it simply tries to require() all the "assets" (styles, images, fonts, OpenGL shaders, etc) as if they were proper javascript-coded modules hence the error message.
Good luck!
Edit:
I think you also want to see this SO question. Importing CSS files in Isomorphic React Components

The project that the OP mentioned is using this:
https://github.com/kriasoft/isomorphic-style-loader
So yes, another loader + an interface to insert and use the styles.

Maybe you doesn't use the sass loader in tour webpack configuration.
Try install this loader:
Sass loader
Example of webpack config:
module.exports = {
...
module: {
loaders: [
{
test: /\.scss$/,
loaders: ["style", "css", "sass"]
}
]
}
sassLoader: {
includePaths: [path.resolve(__dirname, "./some-folder")]
}
};
I can suggest also you to use postcss to apply autoprefixer!

Related

Importing SASS Bootstrap into React

I followed by instructions included in Bootstrap documentation https://getbootstrap.com/docs/4.0/getting-started/download/#npm and installed Bootstrap via Webpack.
Then I wanted to import css styles as here https://getbootstrap.com/docs/4.0/getting-started/theming/ AND
I'VE ENCOUNTERED A PROBLEM:
When I adding this import (#import "node_modules/bootstrap/scss/bootstrap";) to my custom.scss file and order sass --watch custom.scss:custom.css in the console I'm getting this two errors:
1) Error: Cannot find module
"-!../../node_modules/css-loader/index.js?{"importLoaders":1}!../../node_modules/postcss-loader/lib/index.js??postcss!../../node_modules/bootstrap/scss"
2)./src/tu_sassy/custom.css Module not found: Can't resolve
'../../node_modules/bootstrap/scss' in
'/home/zebra/Desktop/testowa/src/tu_sassy'
My file structure is similar as in Bootstrap documentation, included as screenshot below.
!For more I need to add that when I delete this import from custom.scss everything works like a charm ...AND is still reusable and non-corrupted to original Bootstrap stylesheet 'my own stylesheet' WHY ?
One quick tip up front. If you want to write inline-code within your StackOverflow post, use backticks (`) around the code. That makes reading your post much easier.
Sass has its own functionality to import from node modules. Webpack Sass loader provides the ~ (tilde) prefix as a way to tell the compiler that it should resolve the path out of the node_modules folder.
#import "~bootstrap/scss/bootstrap";
If you have a dependency tree of packages within node_modues that import sass files, you can also tell Webpack Sass loader to include node_modules for resolving paths:
{
loader: "sass-loader", // compiles Sass to CSS
options: {
includePaths: [
join(dirname(module.filename), 'node_modules')
]
}

How to add styling to a React project

So I've written a really simple React app, but didn't use the create-react-app setup. I wanted to learn on my own how something like CRA actually gets built. I basically just used webpack to build and bundle my React app. Currently, I have a Babel loader to translate my React/JSX, and an "html-loader", for my HTML I guess (I read a tutorial for Webpack that said I needed it, but I still don't understand why I have to translate my HTML? It's HTML, what does it even translate to)?
My project currently has no CSS styling yet, and I want to learn how to add it. But I'm confused as to what loaders I should use. I'm pretty sure I'll need a Less loader for my .less files, but the Less loader compiles Less to CSS. So would I then need a CSS loader for the compiled less files? And then would I need a style loader for the CSS?
You will need the following loaders :
style-loader
css-loader
less-loader
So basically a webpack config as follow :
module: {
rules: [
{
test: /\.less$/,
use: [
{
loader: "style-loader"
},
{
loader: "css-loader"
},
{
loader: "less-loader"
}
]
}
]
}
Check this answer to know what each loader does.
You might want to consider https://www.styled-components.com/. This library allows you to locate your stylesheet alongside with your react components.
If I am correct, using this library won't change your current webpack config.
If you want a more "traditional" approach for styling your react application, you will need at least two loaders for your webpack config:
style-loader and css-loader.
less and sass loaders will be required if you intend to use css-preprocessors though.

Can react-loadable be used in create-react-app server-side?

I am attempting to do some code-splitting in my create-react-app application that utilizes server side rendering.
I am utilizing 'react-loadable` to do the code-splitting: https://github.com/thejameskyle/react-loadable
As of now I simply have split my Home.js component away from the rest of my app, just to see if it works. In development mode (read: not SSR), it's chunked off and works fine.
However, I can't get things to work on the server. I'm following the guide on their Github page and am stuck because of the webpack changes needed. In create-react-app applications, you don't have access to webpack as it's hidden away.
The error I receive when starting the server is:
return (0, _importInspector.report)(import('../components/home/Home'), {
^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:80:10) ...
I'm pretty sure it's because I don't have webpack configured correctly as stated in the guide.
In the guide, it clearly states for SSR:
First we need Webpack to tell us which bundles each module lives inside. For this there is the React Loadable Webpack plugin.
Import the ReactLoadablePlugin from react-loadable/webpack and include it in your webpack config. Pass it a filename for where to store the JSON data about our bundles.
// webpack.config.js
import { ReactLoadablePlugin } from 'react-loadable/webpack';
export default {
plugins: [
new ReactLoadablePlugin({
filename: './dist/react-loadable.json',
}),
],
};
I don't think this is possible without ejecting.
Anyone have any idea if react-loadable can be used in a create-react-app server-side-rendered application?
import these modules at the top of your server file
require('ignore-styles');
require('babel-polyfill')
require('babel-register')({
ignore: [ /(node_modules)/ ],
presets: ['es2015', 'react-app'],
plugins: [
'syntax-dynamic-import',
'dynamic-import-node',
'react-loadable/babel'
]
});

Webpack + Angular2 AOT: Uncaught SyntaxError: Unexpected token import

in this set-up, how do you transpile the angular2 library being imported from the generated ngfactory files?
the current app is a combination of the webpack + aot cookbook based on the angular docs
angular.io/docs/ts/latest/cookbook/aot-compiler.html
angular.io/docs/ts/latest/guide/webpack.html
I have a working POC where you can replicate the issue from this repo:
https://github.com/jetlogs/Angular2-AOT-Localization
after you've done the compilation / bundling, you can open the 2 files:
non-aot.html - this is the non-aot version of the same app, and it loads fine
aot.html - this file fails with:
ng_module_factory.js?95b1:13 Uncaught SyntaxError: Unexpected token import
Expected behavior
the expected behavior is that aot.html and non-aot.html should have the same behavior
Minimal reproduction of the problem with instructions
clone the repo, then
run these commands on the working directory:
npm install
npm postinstall
npm run build
then open aot.html to reproduce the issue
Is there any way on how to fix the import statements from the imported angular2 libraries? Thanks
UPDATE:
I've tried transpiling the angular2 source files which are in ES2015 by using the babel-loader:
{
test: /\.js$/,
loader: 'babel',
include: [
/node_modules(\\|\/)#angular/
],
exclude: [
/\.umd\.js$/
],
query: {
presets: ['es2015']
}
},
it now compiles without issues with ES6 incompatibilities, however, it now encounters a new error only for aot.html:
core.umd.js?e2a5:3272Uncaught Error: No provider for NgZone!
any reason why transpiled angular2 source codes being referenced by the AOT compiler are cdausing NgZone issues?
I've updated the repo above to reflect my latest changes
UPDATE2: 10/13/16
Updated to Angular 2.1
still the same issue
The System.import syntax used in ng_module_factory.js is ES6 style module loading. Webpack 1, which you are probably using, does not support this syntax.
A workaround might be to transpile the Angular ES6 modules to ES5 with require() syntax, but you already tried this without success.
However you might consider switching to Webpack 2, which fully supports ES6 style imports and is very close to its stable release. The compilation worked for me this way without changing anything except for the webpack config which uses a new syntax for some parts.
For me it was a wrong import generated by IDE:
import { Component, Output } from "#angular/core/src/metadata/directives";
Instead of:
import { Component, Output } from "#angular/core";

Webpack - include css only in development bundle (not production)

When I create my production bundle I do not require any stylesheets in javascript, they are included in index.html. The stylesheets are compiled with a grunt watch from sass to a bundle.css.
While developing I use webpack dev server. Now I want to include the css in the javascript bundle for hot module replacement, but without changing any existing javascript files.
The dev server is using dedicated index.html and webpack.config files, so preferably that's where I include the css bundle. Is this possible?
Maybe it's worth mentioning that I'm using React.
Answer: It looks like you can change the entry[] of webpack.config (example), to access a different .js file. Try creating referencing two different .js entry files for your respective webpack.config files, to import a different CSS file or omit the import line entirely. This compromises DRY, but does what you want.
React shouldn't make any difference.
Hot module is a red herring; it's implemented as a plugin, independently of the above:
plugins: [
...
new webpack.HotModuleReplacementPlugin());
],
Omitting the CSS module loader in webpack.config.dev wouldn't work.
module: {
loaders: [
...
{test: /(\.css|\.scss)$/, loaders: ['style', 'css?sourceMap', 'sass?sourceMap']}
]
}
because it would cause a parse error in import 'path/to/my.css' in index.js

Resources