webpack fails to compile JSX - angularjs

This is the error message that I get (I removed part of the file path for security reasons):
ERROR in ./react-components/MyComponent.js
Module parse failed: /home/vagrant/src/***/react-
components/MyComponent.js Unexpected token (6:6)
You may need an appropriate loader to handle this file type.
| render() {
| return (
| <div>
| <p>FooBar: {this.props.fooBar}</p>
| <p>Baz: {this.props.baz}</p>
# ./client/app/app.module.js 52:19-64
# ./client/app/index.js
Right now, all I'm trying to do is to just allow a React component to live inside an Angular 1.X project. This is what the webpack config looks like:
webpack.make.js:
config.module = {
rules: [{
// JS LOADER
// Reference: https://github.com/babel/babel-loader
// Transpile .js files using babel-loader
// Compiles ES6 and ES7 into ES5 code
test: /\.js$/,
use: [{
loader : 'babel-loader',
options : {
shouldPrintComment(commentContents) {
// keep `/*#ngInject*/`
return /#ngInject/.test(commentContents);
},
plugins : TEST ?
[[ 'istanbul', { 'exclude' : [ '**/*.spec.js'] }]]
: [],
presets : ['es2015', 'react', 'stage-0']
}
}],
include: [
path.resolve(__dirname, 'client/')
]
},{
// ASSET LOADER
// Reference: https://github.com/webpack/file-loader
// Copy png, jpg, jpeg, gif, svg, woff, woff2, ttf, eot files to output
// Rename the file using the asset hash
// Pass along the updated reference to your code
// You can add here any file extension you want to get copied to your output
test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)([\?]?.*)$/,
loader: 'file-loader'
}, {
// HTML LOADER
// Reference: https://github.com/webpack/raw-loader
// Allow loading html through js
test: /\.html$/,
loader: 'raw-loader'
}, {
// CSS LOADER
// Reference: https://github.com/webpack/css-loader
// Allow loading css through js
//
// Reference: https://github.com/postcss/postcss-loader
// Postprocess your css with PostCSS plugins
test: /\.css$/,
loader: !TEST
// Reference: https://github.com/webpack/extract-text-webpack-plugin
// Extract css files in production builds
//
// Reference: https://github.com/webpack/style-loader
// Use style-loader in development for hot-loading
? ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
'css-loader',
{
// PostCSS
// Reference: https://github.com/postcss/autoprefixer-core
// Add vendor prefixes to your css
loader: 'postcss-loader',
options : {
plugins : [
autoprefixer({browsers: ['last 2 version']})
]
}
}
]
})
// Reference: https://github.com/webpack/null-loader
// Skip loading css in test mode
: 'null-loader'
}, {
// SASS LOADER
// Reference: https://github.com/jtangelder/sass-loader
test: /\.(scss|sass)$/,
loader : ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
'css-loader',
{
// PostCSS
// Reference: https://github.com/postcss/autoprefixer-core
// Add vendor prefixes to your css
loader: 'postcss-loader',
options : {
plugins : [
autoprefixer({browsers: ['last 2 version']})
]
}
},
{
loader : 'sass-loader',
options: {
outputStyle: 'compressed',
precision: 10,
sourceComments: false
}
}
]
}),
include: [
path.resolve(__dirname, 'client/app/app.scss')
]
}, {
// Imports Loader
// This allows the CodeMirror json linter to find jsonlint, which it expects to be global
test: require.resolve('codemirror/addon/lint/json-lint'),
use: 'imports-loader?jsonlint=jsonlint-mod'
}
]
};
And here is my .babelrc:
{
"presets": ["es2015", "react", "stage-3", "stage-0"]
}
I've tried both stage-3 and stage-0, but I still get the same error. I made sure to install babel-preset-react via npm. There's nothing wrong with the JSX in the JS file, as it's a simple React component that's used as example code from a repository that I'm using. I've gotten to a point where I'm not sure where to look next.

I forgot to add path.resolve(__dirname, 'react-components') in the includes object, where the JS file in question resides.

Related

React phone number input is causing a webpack error on cypress

When i tried run a cypress test that use a react-phone-number-input a webpack error appears, this error only appears in cypress, my react project don't show this error and works fine, is there a solution in webpack or cypress that can remove this error?
Error: Webpack Compilation Error
./node_modules/react-phone-number-input/style.css 2:0
Module parse failed: Unexpected token (2:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| /* CSS variables. */
> :root {
| --PhoneInputCountrySelect-marginRight: 0.35em;
| --PhoneInputCountrySelectArrow-width: 0.3em;
# ./src/components/InputPhoneNumber/index.js 15:0-44
# ./src/components/SignUpForm/index.js
# ./src/components/ProductForm/index.js
# ./src/tests/ProductForm.spec.js
My Webpack config is this
const CopyWebpackPlugin = require('copy-webpack-plugin')
module.exports = {
plugins: [
new CopyWebpackPlugin({
patterns: [
{ from: 'public' }
]
})
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.css$/i,
use: ['style-loader', 'css-loader']
},
{
test: /\.s[ac]ss$/i,
use: [
{
loader: 'style-loader' // inject CSS to page
},
{
loader: 'css-loader' // translates CSS into CommonJS modules
},
{
loader: 'postcss-loader', // Run postcss actions
options: {
plugins: function () { // postcss plugins, can be exported to postcss.config.js
return [
require('autoprefixer')
]
}
}
},
{
loader: 'sass-loader' // compiles Sass to CSS
}
]
}
]
}
}
The css-loader doesn’t compile css root parameters.
This answer will help you solve the problem
https://github.com/webpack-contrib/css-loader/issues/69#issuecomment-108597013

React Module parse failed: Unexpected character '#'

I am getting an error when trying to import the following in my react component:
import FontIconPicker from '#fonticonpicker/react-fonticonpicker';
import '#fonticonpicker/react-fonticonpicker/dist/fonticonpicker.base-theme.react.css';
I'm using this module: https://fonticonpicker.github.io/react-fonticonpicker/
I get this error:
./node_modules/#fonticonpicker/react-fonticonpicker/dist/fonticonpicker.base-theme.react.css
Module parse failed: Unexpected character '#' (18:0) You may need an
appropriate loader to handle this file type. | * | / |
#font-face{font-family:fontIconPicker;src:url(assets/fontIconPicker.ttf)
format("truetype"),url(assets/fontIconPicker.woff)
format("woff"),url(assets/fontIconPicker.svg#fontIconPicker)
format("svg");font-weight:400;font-style:normal}[class="
fipicon-"],[class^=fipicon-]{font-family:fontIconPicker!important;speak:none;font-style .......
The error can be reproduced with my code from github: https://github.com/gregbia/my-app
Use npm install, and npm start and the error will show.
My webpack looks like this:
/**
* Webpack Configuration
*
* Working of a Webpack can be very simple or complex. This is an intenally simple
* build configuration.
*
* Webpack basics — If you are new the Webpack here's all you need to know:
* 1. Webpack is a module bundler. It bundles different JS modules together.
* 2. It needs and entry point and an ouput to process file(s) and bundle them.
* 3. By default it only understands common JavaScript but you can make it
* understand other formats by way of adding a Webpack loader.
* 4. In the file below you will find an entry point, an ouput, and a babel-loader
* that tests all .js files excluding the ones in node_modules to process the
* ESNext and make it compatible with older browsers i.e. it converts the
* ESNext (new standards of JavaScript) into old JavaScript through a loader
* by Babel.
*
* TODO: Instructions.
*
* #since 1.0.0
*/
const paths = require( './paths' );
const autoprefixer = require( 'autoprefixer' );
const ExtractTextPlugin = require( 'extract-text-webpack-plugin' );
// Extract style.css for both editor and frontend styles.
const blocksCSSPlugin = new ExtractTextPlugin( {
filename: './dist/blocks.style.build.css',
} );
// Extract editor.css for editor styles.
const editBlocksCSSPlugin = new ExtractTextPlugin( {
filename: './dist/blocks.editor.build.css',
} );
// Configuration for the ExtractTextPlugin — DRY rule.
const extractConfig = {
use: [
// "postcss" loader applies autoprefixer to our CSS.
{ loader: 'raw-loader' },
{
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: [
autoprefixer( {
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
} ),
],
},
},
// "sass" loader converts SCSS to CSS.
{
loader: 'sass-loader',
options: {
// Add common CSS file for variables and mixins.
data: '#import "./src/common.scss";\n',
outputStyle: 'nested',
},
},
],
};
// Export configuration.
module.exports = {
entry: {
'./dist/blocks.build': paths.pluginBlocksJs, // 'name' : 'path/file.ext'.
},
output: {
// Add /* filename */ comments to generated require()s in the output.
pathinfo: true,
// The dist folder.
path: paths.pluginDist,
filename: '[name].js', // [name] = './dist/blocks.build' as defined above.
},
// You may want 'eval' instead if you prefer to see the compiled output in DevTools.
devtool: 'cheap-eval-source-map',
module: {
rules: [
{
test: /\.(js|jsx|mjs)$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
// #remove-on-eject-begin
babelrc: false,
presets: [ require.resolve( 'babel-preset-cgb' ) ],
// #remove-on-eject-end
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true,
},
},
},
{
test: /style\.s?css$/,
exclude: /(node_modules|bower_components)/,
use: blocksCSSPlugin.extract( extractConfig ),
},
{
test: /editor\.s?css$/,
exclude: /(node_modules|bower_components)/,
use: editBlocksCSSPlugin.extract( extractConfig ),
},
],
},
// Add plugins.
plugins: [ blocksCSSPlugin, editBlocksCSSPlugin ],
stats: 'minimal',
// stats: 'errors-only',
// Add externals.
externals: {
react: 'React',
'react-dom': 'ReactDOM',
ga: 'ga', // Old Google Analytics.
gtag: 'gtag', // New Google Analytics.
jquery: 'jQuery', // import $ from 'jquery' // Use the WordPress version.
},
};
Actually, I'm so surprised that you used SCSS webpack configs beside the PostCSS because with a little configuration you can pre-process your CSSes and then post-process them to a compressed version by SCSS syntax. I set a config you in this link. I know it is not your main problem but I think your project configuration is not optimized.
The above link of webpack config will help you to make your configuration better and you can see the webpack configs of fonts. any way...
For your exact error, you should fix your font configuration on webpack just like below:
{
test: /\.(woff|woff2|eot|ttf|svg)$/,
exclude: /node_modules/,
loader: 'file-loader',
options: {
limit: 1024,
name: '[name].[ext]',
publicPath: 'dist/assets/',
outputPath: 'dist/assets/'
}
},
Update after work on the repo:
I write the webpack.config.dev.js file like below:
const paths = require('./paths');
const externals = require('./externals');
const autoprefixer = require('autoprefixer');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
// Extract style.css for both editor and frontend styles.
const blocksCSSPlugin = new ExtractTextPlugin({
filename: './dist/blocks.style.build.css',
});
// Extract editor.css for editor styles.
const editBlocksCSSPlugin = new ExtractTextPlugin({
filename: './dist/blocks.editor.build.css',
});
// Configuration for the ExtractTextPlugin — DRY rule.
const extractConfig = {
fallback: 'style-loader',
use: [
// "postcss" loader applies autoprefixer to our CSS.
{loader: 'css-loader'},
{
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: [
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
}),
],
},
},
// "sass" loader converts SCSS to CSS.
{
loader: 'sass-loader',
options: {
// Add common CSS file for variables and mixins.
data: '#import "./src/common.scss";\n',
outputStyle: 'nested',
},
},
],
};
// Export configuration.
module.exports = {
entry: {
'./dist/blocks.build': paths.pluginBlocksJs, // 'name' : 'path/file.ext'.
},
output: {
// Add /* filename */ comments to generated require()s in the output.
pathinfo: true,
// The dist folder.
path: paths.pluginDist,
filename: '[name].js', // [name] = './dist/blocks.build' as defined above.
},
// You may want 'eval' instead if you prefer to see the compiled output in DevTools.
devtool: 'cheap-eval-source-map',
module: {
rules: [
{
test: /\.(js|jsx|mjs)$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
// #remove-on-eject-begin
babelrc: false,
presets: [require.resolve('babel-preset-cgb')],
// #remove-on-eject-end
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true,
},
},
},
{
test: /style\.s?css$/,
exclude: /(node_modules|bower_components)/,
use: blocksCSSPlugin.extract(extractConfig),
},
{
test: /editor\.s?css$/,
exclude: /(node_modules|bower_components)/,
use: editBlocksCSSPlugin.extract(extractConfig),
},
{
test: /\.css$/,
include: /(node_modules\/#fonticonpicker\/react-fonticonpicker\/dist)/,
loaders: ['style-loader', 'css-loader']
},
{
test: /\.(woff|woff2|eot|ttf|svg)$/,
include: /(node_modules\/#fonticonpicker\/react-fonticonpicker\/dist)/,
loader: 'file-loader',
options: {
limit: 1024,
name: '[name].[ext]',
publicPath: 'dist/assets/',
outputPath: 'dist/assets/'
}
}
],
},
// Add plugins.
plugins: [blocksCSSPlugin, editBlocksCSSPlugin],
stats: 'minimal',
// stats: 'errors-only',
// Add externals.
externals: externals,
};
And also install css-loader and file-loader.
npm install file-loader css-loader
Hint: it seems fonts need to have an outputPath in webpack configuration.
The problem is webpack is not loading your fonts #font-face in node_modules. You are excluding the loading of css from node_modules. But your #fonticonpicker/react-fonticonpicker/dist/fonticonpicker.base-theme.react.css is in node_modules.
Change this snippet in your webpack config
{
test: /style\.s?css$/,
exclude: /(node_modules|bower_components)/,
use: blocksCSSPlugin.extract( extractConfig ),
},
{
test: /editor\.s?css$/,
exclude: /(node_modules|bower_components)/,
use: editBlocksCSSPlugin.extract( extractConfig ),
},
to
{
test: /style\.s?css$/,
use: blocksCSSPlugin.extract( extractConfig ),
},
{
test: /editor\.s?css$/,
use: editBlocksCSSPlugin.extract( extractConfig ),
},
{ test: /(\.css$)/, // you need to load all css imported from node_modules
loaders: ['style-loader', 'css-loader', 'postcss-loader']
}
Seems like you're missing css-loader for .css stored in node_modules. That is why you are facing this issue. Run npm i -D css-loader and add this rule to your node_modules > cgb-scrips > config > webpack.config.<env>.js file:
module: {
rules: [
// ...
{
test: /\.css$/,
use: [
{ loader: 'raw-loader' },
{ loader: 'css-loader' },
]
},
// ...
],
},
Alternatively, to skip editing webpack.config.js you could simply import your files like so:
import 'raw-loader!css-loader!#fonticonpicker/react-fonticonpicker/dist/fonticonpicker.base-theme.react.css';
import 'raw-loader!css-loader!#fonticonpicker/react-fonticonpicker/dist/fonticonpicker.material-theme.react.css';
Your loader config in webpack doesn't match the CSS file Route.
import '#fonticonpicker/react-fonticonpicker/dist/fonticonpicker.base-theme.react.css';
It is neither style.css or editor.css. Hence you get an error. Also you are ignoring node_modules in your webpack loader config but you import the css from node_modules.
Adding
{
test: /react\.s?css$/,
use: [{
loader: 'css-loader',
options: {
modules: true
}
}],
},
should work

Import Library Stylesheets With Babel-Plugin-React-Css-Modules

I am trying to include another library's css for their component in my own application. For reference, I am trying to use this data table library: https://github.com/filipdanic/spicy-datatable.
In the docs, it states Out of the box, spicy-datatable is bare-bones. Include this CSS starter file in your project to get the look from the demo. Edit it to suit your needs.
I tried to import the style sheet at the top of the component that I am building like this: import * as spicy from 'spicy-datatable/src/sample-styles.css'; in my own component file. It was not styled. I tried putting the raw code into my index.scss file in my assets/styles folder - did not work. I tried putting it in my own styles file ./component.scss - did not work.
I have them currently set up like:
import * as styles from './component.scss';
import * as spicy from 'spicy-datatable/src/sample-styles.css';
and am getting an error:
Module parse failed: Unexpected token (4:0)
You may need an appropriate loader to handle this file type.
webpack.config.js
const dirNode = 'node_modules';
const dirApp = path.join(__dirname, 'client');
const dirAssets = path.join(__dirname, 'assets');
/**
* Webpack Configuration
*/
module.exports = {
entry: {
vendor: ['lodash'],
bundle: path.join(dirApp, 'index')
},
resolve: {
modules: [dirNode, dirApp, dirAssets]
},
plugins: [],
module: {
rules: [
// BABEL
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /(node_modules)/,
options: {
compact: true
}
},
// CSS / SASS
{
test: /\.(scss)$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 1,
modules: true,
localIdentName: '[path]___[name]__[local]___[hash:base64:5]'
}
},
'sass-loader'
]
},
// IMAGES
{
test: /\.(jpe?g|png|gif)$/,
loader: 'file-loader',
options: {
name: '[path][name].[ext]'
}
}
]
}
};
.babelrc
"plugins": [
[
"react-css-modules",
{
"filetypes": {
".scss": {
"syntax": "postcss-scss"
}
},
"webpackHotModuleReloading": true
}
]
I'm not sure if I need to add something to specifically handle .css files, this is my first time working with CSS Modules. I thought react-css-modules did that so I'm not quite sure why the CSS file isn't loading correctly.
Edit:
Edited my webpack around to include CSS:
{
test: /\.(css)$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[path]___[name]__[local]___[hash:base64:5]'
}
}
]
},
Error is gone, but styles still do not appear.
Could you try changing below:
import * as spicy from 'spicy-datatable/src/sample-styles.css';
to
import from 'spicy-datatable/src/sample-styles.css';
If you are using CSS-Modules, try below:
import spicy from 'spicy-datatable/src/sample-styles.css';
and then use the style on JSX element like below:
<h1 className={classes.<className in CSS here>}>
I setup a codesandbox with the spicy-datatable library and imported the styles and looks like it applied. The styles are in "Hello.css" file and it is imported in "index.js".
https://codesandbox.io/s/4j31xj3689
If library doesn't use css-modules (uses className attribute instead of styleName) we need to disable modules for imported css, so the class names will remain unchanged. This can be done in 2 ways:
Modify your Webpack config
module: {
rules: [
{
test: /\.(css)$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: false
}
}
]
},
...
]
}
Import library css directly into your scss stylesheet (thanks to this answer pointing out how to perform proper .css import). Make sure to exclude .css file extension from import line. :global directive will prevent css-modules to modify class names for all styles within this directive.
:global {
#import "~library-module-name/.../CssFileWithoutExtension";
}

How to setup react app with SCSS? (Errors)

I am trying to setup my react project so I can use SASS in the SCSS format.
This is in my webpack.config.dev.js:
{
test: /\.scss$/,
exclude: /node_modules/,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
},
},
{
loader: require.resolve('sass-loader'),
}
]
}
I import the scss files into my jsx in two different ways:
import './index.scss';
import css from './ModalWrapper.scss';
When I run the app I am currently getting the error:
./src/index.scss
Module build failed:
body {
^
Invalid CSS after "m": expected 1 selector or at-rule, was "module.exports = __"
in /pathtoapp/web/src/index.scss (line 1, column 1)
It appears me, that one, react is trying to interpret the SCSS as CSS which should work. In addition, react believes that body is not valid CSS. There, I would believe that neither CSS or SCSS are being loaded correctly.
Any help would be appreciated. There are quite a few unanswered questions to this problem.
If you are on Webpack 3, add this to module.rules
{
test: /\.scss$/,
loader: [
require.resolve('style-loader'),
require.resolve('css-loader'),
require.resolve('sass-loader'),
]
},
And then add the file loader and make sure to add .scss to the array of the key exclude like this
{
loader: require.resolve('file-loader'),
// Exclude `js` files to keep "css" loader working as it injects
// it's runtime that would otherwise processed through "file" loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/\.js$/, /\.html$/, /\.json$/, /\.scss$/,],
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
}
And of course, make sure you have style-loader, sass-loader, css-loader and file-loader in you package.json. This code snippet worked for me when using the latest version of create-react-app.
This is what ended up working for me:
{
test: /\.scss$/,
use: [{
loader: 'style-loader'
}, {
loader: 'css-loader',
options: {
modules: true,
sourceMap: true,
localIdentName: "[local]___[hash:base64:5]",
},
}, {
loader: 'sass-loader',
options: {
outputStyle: "expanded",
sourceMap: true,
},
}]
},
I'm sure the other answers are just as good, but for maximum brevity, this works for me (I erased some of the internal webpack.config.dev.js comments presumably made by the create react folks):
module: {
strictExportPresence: true,
rules: [
{
test: /\.scss/,
use: ['style-loader','css-loader', 'sass-loader']
},...
I don't know if it matters, but I put this on the top. Also, yes, make sure to add the scss file to the excluded array as mentioned above.

Webpack loader fails when importing .css in react_on_rails app?

I am trying to use react-datetime on my react-on-rails app. To make the datetime work out of the box, I need to import the CSS mentioned on their GH page.
On my app, I copy/paste the CSS into a file I named DateTime.css:
...
import DateTime from 'react-datetime';
import '../../schedules/stylesheets/DateTime.css';
...
export default class AddDate extends React.Component {
But it gives me this error:
VM45976:1 Uncaught Error: Module parse failed: /Users/some/path/to/my/project/App/components/schedules/stylesheets/DateTime.css Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
| .rdt {
| position: relative;
| }
It seems like the CSS loader is not working. I tried this on pure react app (create-react-app) and it worked. It broke when I did it inside react_on_rails.
This is my webpack config atm (standard out-of-the-box react_on_rails):
const webpack = require('webpack');
const { resolve } = require('path');
const ManifestPlugin = require('webpack-manifest-plugin');
const webpackConfigLoader = require('react-on-rails/webpackConfigLoader');
const configPath = resolve('..', 'config');
const { devBuild, manifest, webpackOutputPath, webpackPublicOutputDir } =
webpackConfigLoader(configPath);
const config = {
context: resolve(__dirname),
entry: {
'webpack-bundle': [
'es5-shim/es5-shim',
'es5-shim/es5-sham',
'babel-polyfill',
'./app/bundles/App/startup/registration',
],
},
output: {
// Name comes from the entry section.
filename: '[name]-[hash].js',
// Leading slash is necessary
publicPath: `/${webpackPublicOutputDir}`,
path: webpackOutputPath,
},
resolve: {
extensions: ['.js', '.jsx'],
},
plugins: [
new webpack.EnvironmentPlugin({
NODE_ENV: 'development', // use 'development' unless process.env.NODE_ENV is defined
DEBUG: false,
}),
new ManifestPlugin({ fileName: manifest, writeToFileEmit: true }),
],
module: {
rules: [
{
test: require.resolve('react'),
use: {
loader: 'imports-loader',
options: {
shim: 'es5-shim/es5-shim',
sham: 'es5-shim/es5-sham',
},
},
},
{
test: /\.jsx?$/,
use: 'babel-loader',
exclude: /node_modules/,
},
{
test: /\.css$/,
use: 'css-loader',
exclude: /node_modules/,
},
],
],
},
};
module.exports = config;
if (devBuild) {
console.log('Webpack dev build for Rails'); // eslint-disable-line no-console
module.exports.devtool = 'eval-source-map';
} else {
console.log('Webpack production build for Rails'); // eslint-disable-line no-console
}
I am very new in webpack, and not sure how to I can add loaders to make it work, how can I apply the DateTime.css file that I have to be applied to react-datetime?
EDIT: added css-loader (also updated the webpack above). It is no longer complaining that I don't have the correct loader, but the CSS does not work.
{
test: /\.jsx?$/,
use: 'babel-loader',
exclude: /node_modules/,
},
{
test: /\.css$/,
use: 'css-loader',
exclude: /node_modules/,
},
],
There are 2 conceptually different ways to approach this.
1. Using CSS modules.
This way your CSS will end up bundled with your JS and as soon as webpack loads that JS module/bundle it will automatically append CSS style element into the head.
In my project I have this rule to do exactly that (note that we use both css-loader and style-loader):
{
test: /\.css$/,
use: ['style-loader', {
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[path][name]__[local]--[hash:base64:5]'
}
}]
}
More on css-loader modules at this link.
2. Using ExtractTextPlugin. This way all your CSS will be extracted into a separate file. The configuration requires 2 things: a plugin and loaders configuration created by the plugin:
const ExtractTextPlugin = require('extract-text-webpack-plugin');
// Add this to your webpack plugins array
new ExtractTextPlugin('styles.css')
And add this to your rules:
{
test: /\.css$/,
exclude: /node_modules/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader']
})
}
This will create one single styles.css file and put all CSS you import from JS into that file.

Resources