Module not found: Can't resolve 'style' - javascript

I am trying to configure css modules using sass. I have followed some tutorials but none seem to work. The webpack config was mostly created by create-react-scripts. I seemed to getting this error "Module not found: Can't resolve 'style'" Any help would be great. The error seems to generated at the import statement in my Modal.js file below. (import styles from "../css/modal.scss";)
I have installed sass loader. My package.json file can be found below.
webpack.config.dev.js:
'use strict';
const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const getClientEnvironment = require('./env');
const paths = require('./paths');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
// Webpack uses `publicPath` to determine where the app is being served from.
// In development, we always serve from the root. This makes config easier.
const publicPath = '/';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
const publicUrl = '';
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);
// This is the development configuration.
// It is focused on developer experience and fast rebuilds.
// The production configuration is different and lives in a separate file.
module.exports = {
// You may want 'eval' instead if you prefer to see the compiled output in DevTools.
// See the discussion in https://github.com/facebookincubator/create-react-app/issues/343.
devtool: 'cheap-module-source-map',
// These are the "entry points" to our application.
// This means they will be the "root" imports that are included in JS bundle.
// The first two entry points enable "hot" CSS and auto-refreshes for JS.
entry: [
// Include an alternative client for WebpackDevServer. A client's job is to
// connect to WebpackDevServer by a socket and get notified about changes.
// When you save a file, the client will either apply hot updates (in case
// of CSS changes), or refresh the page (in case of JS changes). When you
// make a syntax error, this client will display a syntax error overlay.
// Note: instead of the default WebpackDevServer client, we use a custom one
// to bring better experience for Create React App users. You can replace
// the line below with these two lines if you prefer the stock client:
// require.resolve('webpack-dev-server/client') + '?/',
// require.resolve('webpack/hot/dev-server'),
require.resolve('react-dev-utils/webpackHotDevClient'),
// We ship a few polyfills by default:
require.resolve('./polyfills'),
// Errors should be considered fatal in development
require.resolve('react-error-overlay'),
// Finally, this is your app's code:
paths.appIndexJs,
// We include the app code last so that if there is a runtime error during
// initialization, it doesn't blow up the WebpackDevServer client, and
// changing JS code would still trigger a refresh.
],
output: {
// Next line is not used in dev but WebpackDevServer crashes without it:
path: paths.appBuild,
// Add /* filename */ comments to generated require()s in the output.
pathinfo: true,
// This does not produce a real file. It's just the virtual path that is
// served by WebpackDevServer in development. This is the JS bundle
// containing code from all our entry points, and the Webpack runtime.
filename: 'static/js/bundle.js',
// There are also additional JS chunk files if you use code splitting.
chunkFilename: 'static/js/[name].chunk.js',
// This is the URL that app is served from. We use "/" in development.
publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: info =>
path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebookincubator/create-react-app/issues/253
modules: ['node_modules', paths.appNodeModules].concat(
// It is guaranteed to exist because we tweak it in `env.js`
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebookincubator/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: ['.web.js', '.js', '.json', '.web.jsx', '.jsx'],
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
},
plugins: [
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
new ModuleScopePlugin(paths.appSrc),
],
},
module: {
strictExportPresence: true,
rules: [
// TODO: Disable require.ensure as it's not a standard language feature.
// We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
// { parser: { requireEnsure: false } },
// First, run the linter.
// It's important to do this before Babel processes the JS.
{
test: /\.(js|jsx)$/,
enforce: 'pre',
use: [
{
options: {
formatter: eslintFormatter,
},
loader: require.resolve('eslint-loader'),
},
],
include: paths.appSrc,
},
// ** ADDING/UPDATING LOADERS **
// The "file" loader handles all assets unless explicitly excluded.
// The `exclude` list *must* be updated with every change to loader extensions.
// When adding a new loader, you must add its `test`
// as a new entry in the `exclude` list for "file" loader.
// "file" loader makes sure those assets get served by WebpackDevServer.
// When you `import` an asset, you get its (virtual) filename.
// In production, they would get copied to the `build` folder.
{
exclude: [
/\.html$/,
/\.(js|jsx)$/,
/\.css$/,
/\.json$/,
/\.bmp$/,
/\.gif$/,
/\.jpe?g$/,
/\.png$/,
/\.scss$/
],
loader: require.resolve('file-loader'),
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
// "url" loader works like "file" loader except that it embeds assets
// smaller than specified limit in bytes as data URLs to avoid requests.
// A missing `test` is equivalent to a match.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]',
},
},
// Process JS with Babel.
{
test: /\.(js|jsx)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
// 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,
},
},
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use a plugin to extract that CSS to a file, but
// in development "style" loader enables hot editing of CSS.
{
test: /\.css$/,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
modules: true,
localIdentName: "[name]__[local]___[hash:base64:5]"
},
},
{
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebookincubator/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
}),
],
},
},
],
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback:'style-loader',
use: [
{
loader: 'css-loader',
q: {
modules: true,
sourcemap: true,
importLoaders: 2,
localIdentName: '[name]__[local]__[hash:base64:5]'
}
},
'sass-loader'
]
}),
loaders: [
require.resolve('style-loader'),
require.resolve('css-loader'),
require.resolve('sass-loader')
]
}
// ** STOP ** Are you adding a new loader?
// Remember to add the new extension(s) to the "file" loader exclusion list.
],
},
plugins: [
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In development, this will be an empty string.
new InterpolateHtmlPlugin(env.raw),
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
}),
// Add module names to factory functions so they appear in browser profiler.
new webpack.NamedModulesPlugin(),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
new webpack.DefinePlugin(env.stringified),
// This is necessary to emit hot updates (currently CSS only):
new webpack.HotModuleReplacementPlugin(),
// Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this.
// See https://github.com/facebookincubator/create-react-app/issues/240
new CaseSensitivePathsPlugin(),
// If you require a missing module and then `npm install` it, you still have
// to restart the development server for Webpack to discover it. This plugin
// makes the discovery automatic so you don't have to restart.
// See https://github.com/facebookincubator/create-react-app/issues/186
new WatchMissingNodeModulesPlugin(paths.appNodeModules),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how Webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
new ExtractTextPlugin({'styles.css'}),
],
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
},
// Turn off performance hints during development because we don't do any
// splitting or minification in interest of speed. These warnings become
// cumbersome.
performance: {
hints: false,
},
};
Modal.js file :
import React from "react";
import ReactDOM from "react-dom";
// import styles from "../css/popUpBox.css";
import styles from "../css/modal.scss"; // ERROR HAPPENS HERE!!
...file continues
Package.json :
{
"name": "react-hackboard",
"version": "0.1.0",
"private": true,
"dependencies": {
"autoprefixer": "7.1.1",
"babel-core": "6.25.0",
"babel-eslint": "7.2.3",
"babel-jest": "20.0.3",
"babel-loader": "7.0.0",
"babel-preset-react-app": "^3.0.1",
"babel-runtime": "6.23.0",
"case-sensitive-paths-webpack-plugin": "2.1.1",
"chalk": "1.1.3",
"css-loader": "0.28.4",
"dotenv": "4.0.0",
"eslint": "3.19.0",
"eslint-config-react-app": "^1.0.5",
"eslint-loader": "1.7.1",
"eslint-plugin-flowtype": "2.34.0",
"eslint-plugin-import": "2.2.0",
"eslint-plugin-jsx-a11y": "5.0.3",
"eslint-plugin-react": "7.1.0",
"extract-text-webpack-plugin": "2.1.2",
"file-loader": "0.11.2",
"fs-extra": "3.0.1",
"html-webpack-plugin": "2.29.0",
"jest": "20.0.4",
"node-sass": "^4.5.3",
"object-assign": "4.1.1",
"postcss-flexbugs-fixes": "3.0.0",
"postcss-loader": "2.0.6",
"promise": "7.1.1",
"react": "^15.6.1",
"react-dev-utils": "^3.0.2",
"react-dom": "^15.6.1",
"react-error-overlay": "^1.0.9",
"react-redux": "^5.0.5",
"redux": "^3.7.2",
"redux-createreducer": "^2.0.0",
"redux-thunk": "^2.2.0",
"sass-loader": "^6.0.6",
"style-loader": "0.18.2",
"sw-precache-webpack-plugin": "0.11.3",
"url-loader": "0.5.9",
"webpack": "2.6.1",
"webpack-dev-server": "2.5.0",
"webpack-manifest-plugin": "1.1.0",
"whatwg-fetch": "2.0.3"
},
"scripts": {
"start": "node scripts/start.js",
"build": "node scripts/build.js",
"test": "node scripts/test.js --env=jsdom"
},
"jest": {
"collectCoverageFrom": [
"src/**/*.{js,jsx}"
],
"setupFiles": [
"<rootDir>/config/polyfills.js"
],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.js?(x)",
"<rootDir>/src/**/?(*.)(spec|test).js?(x)"
],
"testEnvironment": "node",
"testURL": "http://localhost",
"transform": {
"^.+\\.(js|jsx)$": "<rootDir>/node_modules/babel-jest",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$"
],
"moduleNameMapper": {
"^react-native$": "react-native-web"
},
"moduleFileExtensions": [
"web.js",
"js",
"json",
"web.jsx",
"jsx"
]
},
"babel": {
"presets": [
"react-app"
]
},
"eslintConfig": {
"extends": "react-app"
},
"devDependencies": {
"node-sass": "^4.5.3",
"sass-loader": "^6.0.6",
"webpack": "^2.6.1"
}
}

It is saying that dependency is not found for the specific loader.
You can resolve it by doing following
yarn add style-loader css-loader sass-loader
Modify your loader config as following:
{
test: /\.scss$/,
include: paths.appSrc,
loaders: [
require.resolve('style-loader'),
require.resolve('css-loader'),
require.resolve('sass-loader')
]
}
This should get scss working.

I had a same problem and I found working solution.
please add these lines of code in "rules" array of your Webpack config file.
{
test: /\.sass$/,
include: paths.appSrc,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
},
},
{
loader: require.resolve('sass-loader')
}
]
},
and for your information,
#import "path/to/sass.file" if you use import statement in one of your sass files and import "path/to/sass.file" for your react component.
Hope this would work well for you too.

Related

Prevent Webpack from dropping my unused code

For example, my javascript file contains function that's only called when I press HTML button. As far as I know, Webpack will treat the function as a 'dead code' because it isn't used anywhere in javascript file and then dropped the code.
So, the question is how can I disable Webpack from dropping the dead code? (or any other way would also helpful)
For more information, I tried following this thread but still can't figure out how:
How to prevent unused code from being dropped during webpack build?
What I also already did was exporting everything inside index.js and import them in main.js along with other things like jquery and mathjs which then be compiled by Webpack. The output file has jquery, mathjs, and only console.log from main.js and general.js.
Even when I set the mode in development or none, the output file doesn't work at all.
// package.json
{
"private": true,
"devDependencies": {
"css-loader": "^6.7.3",
"css-minimizer-webpack-plugin": "^4.2.2",
"html-loader": "^4.2.0",
"html-webpack-plugin": "^5.5.0",
"mini-css-extract-plugin": "^2.7.2",
"purgecss-webpack-plugin": "^5.0.0",
"terser-webpack-plugin": "^5.3.6",
"uglify-js": "^3.17.4",
"uglifyjs-folder": "^3.2.0",
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1"
},
"dependencies": {
"jquery": "^3.6.3",
"mathjs": "^11.5.0"
}
}
Here's my webpack.config.js (though I don't think there's problem here):
// webpack.config.js
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
module.exports = [
{
mode: 'production',
module: {
rules: [
{
test: /.html$/i,
loader: "html-loader",
},
{
test: /.s?css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"],
},
],
},
optimization: {
minimizer: [...,new CssMinimizerPlugin()]
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.php'
}),
new MiniCssExtractPlugin({
filename: '[name].[contenthash].css'
}),
],
},
]
Here's some part of the javascript file:
// main.js
import 'jquery';
import { evaluate } from 'mathjs';
console.log(evaluate('2+3'));
import js from './general.js';
// general.js
export let result;
export function clr() {
$('.input').text('0');
$('.result').text('0').removeClass('visible');
$('.input').addClass('highlight');
$('.result').removeClass('highlight');
return result = 0;
}
...
console.log('javascript loaded');
// output.js
// (...last part of the code, just to show that the javascript files are compiled successfully)
.......ImmutableDenseMatrix:Eb,Index:Ab,Spa:$b,Unit:Gb,SymbolNode:kN,FunctionNode:zN,Help:UN,Parser:GN}),FN.createProxy(hN),console.log("javascript loaded"),console.log($N("2+3"))})()})();
(I'm sorry if I can't explain it well. If there's something that I missing please let me know)

How to use babel with webpack for ie11 compatibility

It's the first time i use webpack with babel, my goal is to make my small template app compatible with ie11.
For some reason I ignore, my JS does not work at all in ie11 even though I did set it as a target in my config. To test it, I use a ie11 on the internet but I don't have access to the stack errors since I'm on MacOS.
What am I missing here?
Source code for more info : https://github.com/VelynnXV/Front-End-Workflow
website : https://nifty-noether-cafbd5.netlify.app/
app.js
import regeneratorRuntime from "regenerator-runtime";
async function app() {
console.log('App entry point')
const template = document.getElementById('app')
await new Promise(r => setTimeout(() => r(), 2500))
template.innerHTML = `
<div class="web-container">
<div id="">
Async / awat test
</div>
</div>
`
console.log('App finished')
};
app();
webpack.config.json
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'development',
entry: ['core-js/stable', './src/app.js'],
output: {
path: path.resolve(__dirname, './dist'),
filename: 'app.js',
},
devServer: {
publicPath: "./src/",
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 9000,
},
plugins: [
new HtmlWebpackPlugin({ // will generate the html file WITH app.js
// see plugin here : https://webpack.js.org/plugins/html-webpack-plugin/
template: './src/index.html',
filename: './index.html'
})
],
module: {
rules: [ // set of rules letting webpack know how to handle .xyz files
{
test: /\.m?js$/, // source: https://webpack.js.org/loaders/babel-loader/
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
}
}
],
},
};
babel.config.js
// babel.config.js
module.exports = api => {
return {
plugins: [
"#babel/plugin-proposal-nullish-coalescing-operator",
"#babel/plugin-proposal-optional-chaining",
"#babel/plugin-transform-runtime",
],
presets: [
[
"#babel/preset-env",
{
useBuiltIns: "entry",
corejs:3,
// caller.target will be the same as the target option from webpack
targets: api.caller(caller => caller && caller.target === "node")
? { node: "current" }
: { chrome: "58", ie: "11" }
}
]
]
}
}
package.json
{
"name": "front-end-workflow",
"version": "1.0.0",
"description": "",
"main": "src/app.js",
"scripts": {
"dev": "npm run clean && npm run build && webpack serve",
"build": "webpack",
"clean": "rimraf ./dist"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.12.17",
"#babel/plugin-transform-runtime": "^7.12.17",
"#babel/preset-env": "^7.12.17",
"babel-loader": "^8.2.2",
"css-loader": "^5.0.2",
"html-loader": "^2.1.0",
"html-webpack-plugin": "^5.2.0",
"sass": "^1.32.8",
"sass-loader": "^11.0.1",
"style-loader": "^2.0.0",
"webpack": "^5.23.0",
"webpack-cli": "^4.5.0",
"webpack-dev-server": "^3.11.2"
},
"dependencies": {
"#babel/runtime": "^7.6.3",
"core-js": "^3.3.2"
}
}
You almost have a complete configuration for IE11 support. The only thing you're missing is a target: "es5" option in your webpack configuration. Babel correctly transpiled your files. Webpack also injected all the necessary polyfills. However, you need to tell Webpack when it bundles the code together to use a syntax that your target browser can understand. For whatever reason, Webpack set the default to a version of ES that contained arrow functions. The error that IE11 console was showing (SCRIPT1002:syntax error) was pointing at the very first occurrence of an arrow function in your bundled app.js file.
An extra tip: use comments: false in your babel config to strip the code comments out of your bundle. This can slightly decrease the size of your bundle.
You can git apply this diff in your repo to take the changes in.
diff --git a/babel.config.js b/babel.config.js
index 8d2442b..273176c 100644
--- a/babel.config.js
+++ b/babel.config.js
## -2,6 +2,7 ##
module.exports = api => {
return {
+ comments: false,
plugins: [
"#babel/plugin-transform-runtime",
],
diff --git a/webpack.config.js b/webpack.config.js
index 2243a11..08af521 100644
--- a/webpack.config.js
+++ b/webpack.config.js
## -21,6 +21,7 ## module.exports = {
filename: './index.html'
})
],
+ target: "es5",
module: {
rules: [ // set of rules letting webpack know how to handle .xyz files using loader
// see loaders : https://webpack.js.org/loaders/

Unable to run npm start: "this.htmlWebpackPlugin.getHooks is not a function"

I'm in a bit of a bind and have a very weak background in web development. Recently, I've had to take over the work of a colleague who left and have been studying web development and learning all of the tools while trying to finish the site we were working on. The project uses webpack and react, and I was trying to add in redux when everything went wrong. I updated webpack and some plugins to the most recent versions to be up to date and function with redux. Upon updating, I have run into problem after problem trying to just npm start. I should note that previously, I had been working on the project (without redux) and had made some changes to the website and had everything functional. Since trying to update, I can't even run a dev sever. I've been researching this problem for a week or so, and trying to learn as much as I can about how all of the start-up files actually function, but have yet to find a solution. Any suggestions?
Here's the exact error:
this.htmlWebpackPlugin.getHooks is not a function
npm ERR! code ELIFECYCLE
npm ERR! errno 1
I'm not sure if including my webpack config and npm start will help or not, but here they are as well
Here's my webpack.config.dev
'use strict';
const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const getClientEnvironment = require('./env');
const paths = require('./paths');
// Webpack uses `publicPath` to determine where the app is being served from.
// In development, we always serve from the root. This makes config easier.
const publicPath = '/';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
const publicUrl = '';
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);
// This is the development configuration.
// It is focused on developer experience and fast rebuilds.
// The production configuration is different and lives in a separate file.
module.exports = {
mode: 'production',
// You may want 'eval' instead if you prefer to see the compiled output in DevTools.
// See the discussion in https://github.com/facebookincubator/create-react-app/issues/343.
devtool: 'cheap-module-source-map',
// These are the "entry points" to our application.
// This means they will be the "root" imports that are included in JS bundle.
// The first two entry points enable "hot" CSS and auto-refreshes for JS.
entry: [
// We ship a few polyfills by default:
require.resolve('./polyfills'),
// Include an alternative client for WebpackDevServer. A client's job is to
// connect to WebpackDevServer by a socket and get notified about changes.
// When you save a file, the client will either apply hot updates (in case
// of CSS changes), or refresh the page (in case of JS changes). When you
// make a syntax error, this client will display a syntax error overlay.
// Note: instead of the default WebpackDevServer client, we use a custom one
// to bring better experience for Create React App users. You can replace
// the line below with these two lines if you prefer the stock client:
// require.resolve('webpack-dev-server/client') + '?/',
// require.resolve('webpack/hot/dev-server'),
require.resolve('react-dev-utils/webpackHotDevClient'),
// Finally, this is your app's code:
paths.appIndexJs,
// We include the app code last so that if there is a runtime error during
// initialization, it doesn't blow up the WebpackDevServer client, and
// changing JS code would still trigger a refresh.
],
output: {
// Add /* filename */ comments to generated require()s in the output.
pathinfo: true,
// This does not produce a real file. It's just the virtual path that is
// served by WebpackDevServer in development. This is the JS bundle
// containing code from all our entry points, and the Webpack runtime.
filename: 'static/js/bundle.js',
// There are also additional JS chunk files if you use code splitting.
chunkFilename: 'static/js/[name].chunk.js',
// This is the URL that app is served from. We use "/" in development.
publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: info =>
path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebookincubator/create-react-app/issues/253
modules: ['node_modules', paths.appNodeModules].concat(
// It is guaranteed to exist because we tweak it in `env.js`
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebookincubator/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
},
plugins: [
//new HtmlWebpackPlugin(),
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
],
},
module: {
strictExportPresence: true,
rules: [
// TODO: Disable require.ensure as it's not a standard language feature.
// We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
// { parser: { requireEnsure: false } },
// First, run the linter.
// It's important to do this before Babel processes the JS.
{
test: /\.(js|jsx|mjs)$/,
enforce: 'pre',
use: [
{
options: {
formatter: eslintFormatter,
eslintPath: require.resolve('eslint'),
},
loader: require.resolve('eslint-loader'),
},
],
include: paths.appSrc,
},
{
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
// "url" loader works like "file" loader except that it embeds assets
// smaller than specified limit in bytes as data URLs to avoid requests.
// A missing `test` is equivalent to a match.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]',
},
},
// Process JS with Babel.
{
test: /\.(js|jsx|mjs)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
// 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,
},
},
//scss
{
test: /\.scss$/,
include: paths.appSrc,
loaders: [require.resolve('style-loader'), require.resolve('css-loader'), require.resolve('sass-loader')]
},
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use a plugin to extract that CSS to a file, but
// in development "style" loader enables hot editing of CSS.
{
test: /\.css$/,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
},
},
{
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebookincubator/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
}),
],
},
},
],
},
// "file" loader makes sure those assets get served by WebpackDevServer.
// When you `import` an asset, you get its (virtual) filename.
// In production, they would get copied to the `build` folder.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
// Exclude `js` files to keep "css" loader working as it injects
// its runtime that would otherwise processed through "file" loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/\.sass$/,
/\.(js|jsx|mjs)$/,
/\.html$/,
/\.json$/],
loader: require.resolve('file-loader'),
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
],
},
// ** STOP ** Are you adding a new loader?
// Make sure to add the new loader(s) before the "file" loader.
],
},
plugins: [
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In development, this will be an empty string.
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
}),
new InterpolateHtmlPlugin(env.raw),
// Add module names to factory functions so they appear in browser profiler.
new webpack.NamedModulesPlugin(),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
new webpack.DefinePlugin(env.stringified),
// This is necessary to emit hot updates (currently CSS only):
new webpack.HotModuleReplacementPlugin(),
// Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this.
// See https://github.com/facebookincubator/create-react-app/issues/240
new CaseSensitivePathsPlugin(),
// If you require a missing module and then `npm install` it, you still have
// to restart the development server for Webpack to discover it. This plugin
// makes the discovery automatic so you don't have to restart.
// See https://github.com/facebookincubator/create-react-app/issues/186
new WatchMissingNodeModulesPlugin(paths.appNodeModules),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how Webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
],
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty',
},
// Turn off performance hints during development because we don't do any
// splitting or minification in interest of speed. These warnings become
// cumbersome.
performance: {
hints: false,
},
};
Here's the start.js
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const fs = require('fs');
const chalk = require('chalk');
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const clearConsole = require('react-dev-utils/clearConsole');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const {
choosePort,
createCompiler,
prepareProxy,
prepareUrls,
} = require('react-dev-utils/WebpackDevServerUtils');
const openBrowser = require('react-dev-utils/openBrowser');
const paths = require('../config/paths');
const config = require('../config/webpack.config.dev');
const createDevServerConfig = require('../config/webpackDevServer.config');
const useYarn = fs.existsSync(paths.yarnLockFile);
const isInteractive = process.stdout.isTTY;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// Tools like Cloud9 rely on this.
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
const HOST = process.env.HOST || '0.0.0.0';
if (process.env.HOST) {
console.log(
chalk.cyan(
`Attempting to bind to HOST environment variable: ${chalk.yellow(
chalk.bold(process.env.HOST)
)}`
)
);
console.log(
`If this was unintentional, check that you haven't mistakenly set it in your shell.`
);
console.log();
}
// We attempt to use the default port but if it is busy, we offer the user to
// run on a different port. `choosePort()` Promise resolves to the next free port.
choosePort(HOST, DEFAULT_PORT)
.then(port => {
if (port == null) {
// We have not found a port.
return;
}
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
const appName = require(paths.appPackageJson).name;
const urls = prepareUrls(protocol, HOST, port);
// Create a webpack compiler that is configured with custom messages.
const compiler = createCompiler(webpack, config, appName, urls, useYarn);
// Load proxy config
const proxySetting = require(paths.appPackageJson).proxy;
const proxyConfig = prepareProxy(proxySetting, paths.appPublic);
// Serve webpack assets generated by the compiler over a web sever.
const serverConfig = createDevServerConfig(
proxyConfig,
urls.lanUrlForConfig
);
const devServer = new WebpackDevServer(compiler, serverConfig);
// Launch WebpackDevServer.
devServer.listen(port, HOST, err => {
if (err) {
return console.log(err);
}
if (isInteractive) {
clearConsole();
}
console.log(chalk.cyan('Starting the development server...\n'));
openBrowser(urls.localUrlForBrowser);
});
['SIGINT', 'SIGTERM'].forEach(function(sig) {
process.on(sig, function() {
devServer.close();
process.exit();
});
});
})
.catch(err => {
if (err && err.message) {
console.log(err.message);
}
process.exit(1);
});
Here's the package.json
{
"name": "test-site",
"version": "0.1.0",
"private": true,
"dependencies": {
"#babel/cli": "^7.1.5",
"#babel/preset-react": "^7.0.0",
"#fortawesome/fontawesome-svg-core": "^1.2.8",
"#fortawesome/react-fontawesome": "^0.1.3",
"ajv": "^6.5.5",
"ajv-keywords": "^3.2.0",
"autoprefixer": "7.1.6",
"babel-eslint": "7.2.3",
"babel-jest": "20.0.3",
"babel-plugin-lodash": "^3.3.4",
"babel-plugin-react-transform": "^3.0.0",
"babel-preset-react-app": "^3.1.2",
"babel-runtime": "6.26.0",
"case-sensitive-paths-webpack-plugin": "2.1.1",
"chalk": "1.1.3",
"css-loader": "0.28.7",
"dotenv": "4.0.0",
"dotenv-expand": "4.2.0",
"eslint-config-react-app": "^2.1.0",
"eslint-plugin-flowtype": "2.39.1",
"eslint-plugin-import": "2.8.0",
"eslint-plugin-jsx-a11y": "5.1.1",
"eslint-plugin-react": "7.4.0",
"extract-text-webpack-plugin": "3.0.2",
"fs-extra": "3.0.1",
"interpolate-html-plugin": "^3.0.0",
"jest": "20.0.4",
"jquery": "^3.3.1",
"nodejs-latest": "^1.1.0",
"object-assign": "4.1.1",
"postcss-flexbugs-fixes": "3.2.0",
"postcss-loader": "2.0.8",
"promise": "8.0.1",
"raf": "3.4.0",
"react": "^16.6.3",
"react-addons-css-transition-group": "^15.6.2",
"react-addons-transition-group": "^15.6.2",
"react-art": "^16.6.0",
"react-dev-utils": "^6.1.1",
"react-dom": "^16.6.3",
"react-native": "^0.57.4",
"react-native-web": "^0.9.6",
"react-player": "^1.6.6",
"react-redux": "^5.1.1",
"react-reveal": "^1.2.2",
"react-router": "^4.3.1",
"react-router-dom": "^4.3.1",
"react-router-native": "^4.3.0",
"react-scripts": "^2.1.1",
"react-scrollable-anchor": "^0.6.1",
"react-slick": "^0.23.1",
"react-sticky": "^6.0.3",
"react-toastify": "^4.3.1",
"react-transition-group": "^1.2.1",
"react-unity-webgl": "^7.0.6",
"redux": "^4.0.1",
"redux-thunk": "^2.3.0",
"resolve": "1.6.0",
"serve": "^10.0.2",
"slick-carousel": "^1.8.1",
"style-loader": "0.19.0",
"sw-precache-webpack-plugin": "^0.11.5",
"url-loader": "0.6.2",
"video-react": "^0.13.0",
"whatwg-fetch": "2.0.3",
"x": "^0.1.2"
},
"scripts": {
"start": "node scripts/start.js",
"build": "node scripts/build.js",
"test": "node scripts/test.js --env=jsdom"
},
"babel": {
"presets": [
"es2015",
"#babel/env",
"#babel/react"
],
"plugins": [
"#babel/plugin-proposal-class-properties"
]
},
"devDependencies": {
"#babel/core": "^7.1.6",
"#babel/preset-env": "^7.1.6",
"babel-core": "^6.26.3",
"babel-loader": "^8.0.4",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"eslint": "^4.10.0",
"eslint-loader": "^2.1.1",
"file-loader": "^2.0.0",
"html-webpack-plugin": "^4.0.0-beta.4",
"node-sass": "^4.9.3",
"sass-loader": "^7.1.0",
"webpack": "^4.25.1",
"webpack-cli": "^3.1.2",
"webpack-dev-server": "^3.1.10",
"webpack-manifest-plugin": "^2.0.4"
},
"jest": {
"collectCoverageFrom": [
"src/**/*.{js,jsx,mjs}"
],
"setupFiles": [
"<rootDir>/config/polyfills.js"
],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.{js,jsx,mjs}",
"<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}"
],
"testEnvironment": "node",
"testURL": "http://localhost",
"transform": {
"^.+\\.(js|jsx|mjs)$": "<rootDir>/node_modules/babel-jest",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|mjs|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"
],
"moduleNameMapper": {
"^react-native$": "react-native-web"
},
"moduleFileExtensions": [
"web.js",
"js",
"json",
"web.jsx",
"jsx",
"node",
"mjs"
]
},
"eslintConfig": {
"extends": "react-app",
"globals": {
"gamesparks": true
}
}
}
Sorry for the mountains of code but any help would be great!
I'm having the same problem, while upgrading a React app from v15.X to 16.X. Apparently, InterpolateHtmlPlugin needs to be updated to 4.X in order for this error to disappear but, in our case, that version also breaks compatibility with other libraries of us.
It seems like Node packages are getting crazy and wrecking havoc. I've spent more than 6 working days already trying to upgrade my Webpack, React, Babel, Jest, CRA and ExtReact dependencies. All of them have shipped a major version in the last months and it seems impossible to make them work altogether again.
Node has made JS really powerful, but really tedious and painful to configure and develop. We're embracing everything we didn't like from other languages, and this is a result of it.

React hydrate TypeError: __webpack_require__.i(...) is not a function

I am getting a webpack TypeError when trying to use hydrate() in index.js. The error is not seen when I use ReactDOM.render() instead of hydrate and I am using hydrate for server side rendering.
src/index.js
import React from 'react';
import ReactDOM, { hydrate } from 'react-dom';
import { Provider } from 'react-redux';
import App from './App';
import store from './store/configureStore';
hydrate(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
config/webpack.config.dev.js
'use strict';
const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const getClientEnvironment = require('./env');
const paths = require('./paths');
// Webpack uses `publicPath` to determine where the app is being served from.
// In development, we always serve from the root. This makes config easier.
const publicPath = '/';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
const publicUrl = '';
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);
// This is the development configuration.
// It is focused on developer experience and fast rebuilds.
// The production configuration is different and lives in a separate file.
module.exports = {
// You may want 'eval' instead if you prefer to see the compiled output in DevTools.
// See the discussion in https://github.com/facebookincubator/create-react-app/issues/343.
devtool: 'cheap-module-source-map',
// These are the "entry points" to our application.
// This means they will be the "root" imports that are included in JS bundle.
// The first two entry points enable "hot" CSS and auto-refreshes for JS.
entry: [
// Include an alternative client for WebpackDevServer. A client's job is to
// connect to WebpackDevServer by a socket and get notified about changes.
// When you save a file, the client will either apply hot updates (in case
// of CSS changes), or refresh the page (in case of JS changes). When you
// make a syntax error, this client will display a syntax error overlay.
// Note: instead of the default WebpackDevServer client, we use a custom one
// to bring better experience for Create React App users. You can replace
// the line below with these two lines if you prefer the stock client:
// require.resolve('webpack-dev-server/client') + '?/',
// require.resolve('webpack/hot/dev-server'),
require.resolve('react-dev-utils/webpackHotDevClient'),
// We ship a few polyfills by default:
require.resolve('./polyfills'),
// Errors should be considered fatal in development
require.resolve('react-error-overlay'),
// Finally, this is your app's code:
paths.appIndexJs,
// We include the app code last so that if there is a runtime error during
// initialization, it doesn't blow up the WebpackDevServer client, and
// changing JS code would still trigger a refresh.
],
output: {
// Next line is not used in dev but WebpackDevServer crashes without it:
path: paths.appBuild,
// Add /* filename */ comments to generated require()s in the output.
pathinfo: true,
// This does not produce a real file. It's just the virtual path that is
// served by WebpackDevServer in development. This is the JS bundle
// containing code from all our entry points, and the Webpack runtime.
filename: 'static/js/bundle.js',
// There are also additional JS chunk files if you use code splitting.
chunkFilename: 'static/js/[name].chunk.js',
// This is the URL that app is served from. We use "/" in development.
publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: info =>
path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebookincubator/create-react-app/issues/253
modules: ['node_modules', paths.appNodeModules].concat(
// It is guaranteed to exist because we tweak it in `env.js`
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebookincubator/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: ['.web.js', '.js', '.json', '.web.jsx', '.jsx'],
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
},
plugins: [
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
new ModuleScopePlugin(paths.appSrc),
],
},
module: {
strictExportPresence: true,
rules: [
// TODO: Disable require.ensure as it's not a standard language feature.
// We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
// { parser: { requireEnsure: false } },
// First, run the linter.
// It's important to do this before Babel processes the JS.
{
test: /\.(js|jsx)$/,
enforce: 'pre',
use: [
{
options: {
formatter: eslintFormatter,
},
loader: require.resolve('eslint-loader'),
},
],
include: paths.appSrc,
},
// ** ADDING/UPDATING LOADERS **
// The "file" loader handles all assets unless explicitly excluded.
// The `exclude` list *must* be updated with every change to loader extensions.
// When adding a new loader, you must add its `test`
// as a new entry in the `exclude` list for "file" loader.
// "file" loader makes sure those assets get served by WebpackDevServer.
// When you `import` an asset, you get its (virtual) filename.
// In production, they would get copied to the `build` folder.
{
exclude: [
/\.html$/,
/\.(js|jsx)$/,
/\.css$/,
/\.json$/,
/\.bmp$/,
/\.gif$/,
/\.jpe?g$/,
/\.png$/,
],
loader: require.resolve('file-loader'),
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
// "url" loader works like "file" loader except that it embeds assets
// smaller than specified limit in bytes as data URLs to avoid requests.
// A missing `test` is equivalent to a match.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]',
},
},
// Process JS with Babel.
{
test: /\.(js|jsx)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
// 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,
},
},
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use a plugin to extract that CSS to a file, but
// in development "style" loader enables hot editing of CSS.
{
test: /\.css$/,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
},
},
{
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebookincubator/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
}),
],
},
},
],
},
// ** STOP ** Are you adding a new loader?
// Remember to add the new extension(s) to the "file" loader exclusion list.
],
},
plugins: [
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In development, this will be an empty string.
new InterpolateHtmlPlugin(env.raw),
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
}),
// Add module names to factory functions so they appear in browser profiler.
new webpack.NamedModulesPlugin(),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
new webpack.DefinePlugin(env.stringified),
// This is necessary to emit hot updates (currently CSS only):
new webpack.HotModuleReplacementPlugin(),
// Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this.
// See https://github.com/facebookincubator/create-react-app/issues/240
new CaseSensitivePathsPlugin(),
// If you require a missing module and then `npm install` it, you still have
// to restart the development server for Webpack to discover it. This plugin
// makes the discovery automatic so you don't have to restart.
// See https://github.com/facebookincubator/create-react-app/issues/186
new WatchMissingNodeModulesPlugin(paths.appNodeModules),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how Webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
],
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
},
// Turn off performance hints during development because we don't do any
// splitting or minification in interest of speed. These warnings become
// cumbersome.
performance: {
hints: false,
},
};
package.json
{
"name": "tratoli_backend",
"version": "0.1.0",
"private": true,
"dependencies": {
"autoprefixer": "7.1.1",
"babel-core": "6.25.0",
"babel-eslint": "7.2.3",
"babel-jest": "20.0.3",
"babel-loader": "7.0.0",
"babel-preset-react-app": "^3.0.1",
"babel-runtime": "6.23.0",
"case-sensitive-paths-webpack-plugin": "2.1.1",
"chalk": "1.1.3",
"css-loader": "0.28.4",
"dotenv": "4.0.0",
"eslint": "3.19.0",
"eslint-config-react-app": "^1.0.5",
"eslint-loader": "1.7.1",
"eslint-plugin-flowtype": "2.34.0",
"eslint-plugin-import": "2.2.0",
"eslint-plugin-jsx-a11y": "5.0.3",
"eslint-plugin-react": "7.1.0",
"express": "^4.16.2",
"extract-text-webpack-plugin": "2.1.2",
"file-loader": "0.11.2",
"fixed-data-table": "^0.6.4",
"fixed-data-table-2": "^0.7.17",
"fs-extra": "3.0.1",
"html-webpack-plugin": "2.29.0",
"isomorphic-fetch": "^2.2.1",
"jest": "20.0.4",
"object-assign": "4.1.1",
"postcss-flexbugs-fixes": "3.0.0",
"postcss-loader": "2.0.6",
"promise": "7.1.1",
"react": "^15.6.1",
"react-bootstrap": "^0.31.2",
"react-dev-utils": "^3.0.2",
"react-dom": "^15.6.1",
"react-error-overlay": "^1.0.9",
"react-redux": "^5.0.5",
"react-router": "^4.2.0",
"react-router-dom": "^4.1.2",
"react-router-redux": "next",
"react-select": "^1.0.0-rc.5",
"react-table": "^6.8.0",
"redux": "^3.7.2",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.2.0",
"style-loader": "0.18.2",
"sw-precache-webpack-plugin": "0.11.3",
"url-loader": "0.5.9",
"webpack": "2.6.1",
"webpack-dev-server": "2.5.0",
"webpack-manifest-plugin": "1.1.0",
"webpack-node-externals": "^1.6.0",
"whatwg-fetch": "2.0.3"
},
"scripts": {
"start": "node scripts/start.js",
"build": "node scripts/build.js && npm run ssr",
"test": "node scripts/test.js --env=jsdom",
"start-ssr": "NODE_ENV=production webpack --config ./config/webpack.ssr.config.js",
"ssr": "NODE_ENV=production babel-node server/index.js --presets es2015,stage-2",
"ssr-start": "NODE_ENV=production node dist/server.js"
},
"jest": {
"collectCoverageFrom": [
"src/**/*.{js,jsx}"
],
"setupFiles": [
"<rootDir>/config/polyfills.js"
],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.js?(x)",
"<rootDir>/src/**/?(*.)(spec|test).js?(x)"
],
"testEnvironment": "node",
"testURL": "http://localhost",
"transform": {
"^.+\\.(js|jsx)$": "<rootDir>/node_modules/babel-jest",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$"
],
"moduleNameMapper": {
"^react-native$": "react-native-web"
},
"moduleFileExtensions": [
"web.js",
"js",
"json",
"web.jsx",
"jsx"
]
},
"babel": {
"plugins": [
"css-modules-transform"
],
"presets": [
"react-app"
]
},
"eslintConfig": {
"extends": "react-app"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-plugin-css-modules-transform": "^1.5.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"babel-preset-stage-2": "^6.24.1"
}
}
And this here is the screenshot of the error message I received.
hydrate method is available in React 16(react-dom v16).
You are trying to access it from React 15(react-dom v15.6.1). This method is not available in React 15.
Update your react-dom to version to 16 and it should work fine.

Webpack css-loader not building

I am having difficulty in getting CSS loading using css-loader on my JSX files. I was following the example from:
https://christianalfoni.github.io/react-webpack-cookbook/Loading-CSS.html
This is my JSX
import React from 'react';
import ReactDOM from 'react-dom';
import styles from './styles.css';
class Hello extends React.Component {
render() {
return <div>Hello world!</div>
}
}
var el = document.getElementById('content')
var data = JSON.parse(el.getAttribute('data-attr'))
ReactDOM.render(<Hello data={data} />, el);`
This is my package.json
"devDependencies": {
"babel-core": "^6.3.26",
"babel-loader": "^6.2.0",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"css-loader": "^0.23.1",
"exports-loader": "~0.6.2",
"expose-loader": "~0.6.0",
"grunt": "^0.4.5",
"grunt-babel": "^6.0.0",
"grunt-cli": "^0.1.13",
"grunt-contrib-watch": "^0.6.1",
"grunt-webpack": "^1.0.11",
"history": "^1.17.0",
"imports-loader": "~0.6.3",
"jquery": "^2.1.4",
"lodash": "~3.0.0",
"react": "^0.14.5",
"react-dom": "^0.14.5",
"react-router": "^1.0.3",
"style-loader": "^0.13.0",
"webpack": "^1.12.9",
"webpack-dev-server": "^1.14.0"
},
"dependencies": {
"chunk-manifest-webpack-plugin": "0.0.1",
"grunt-react": "^0.12.3"
}
This is my Webpack.config.js
var path = require('path');
var webpack = require('webpack');
var config = module.exports = {
// the base path which will be used to resolve entry points
context: __dirname,
// the main entry point for our application's frontend JS
entry: './app/frontend/javascripts/entry.js',
stats: {
// Configure the console output
colors: true,
modules: true,
reasons: true
},
progress: true,
keepalive: true,
module: {
loaders: [
{
test: /\.js?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader', // 'babel-loader' is also a legal name to reference
query: { presets: ['es2015', 'react'] }
},
{ test: /\.css$/, loader: "style-loader!css-loader" }
]
},
output: {
// this is our app/assets/javascripts directory, which is part of the Sprockets pipeline
path: path.join(__dirname, 'app', 'assets', 'javascripts'),
// the filename of the compiled bundle, e.g. app/assets/javascripts/bundle.js
filename: 'bundle.js',
// if the webpack code-splitting feature is enabled, this is the path it'll use to download bundles
publicPath: '/assets',
devtoolModuleFilenameTemplate: '[resourcePath]',
devtoolFallbackModuleFilenameTemplate: '[resourcePath]?[hash]',
},
resolve: {
// tell webpack which extensions to auto search when it resolves modules. With this,
// you'll be able to do `require('./utils')` instead of `require('./utils.js')`
extensions: ['', '.js'],
// by default, webpack will search in `web_modules` and `node_modules`. Because we're using
// Bower, we want it to look in there too
modulesDirectories: [ 'node_modules', 'bower_components' ],
},
plugins: [
// we need this plugin to teach webpack how to find module entry points for bower files,
// as these may not have a package.json file
new webpack.ResolverPlugin([
new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('.bower.json', ['main'])
]),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
}),
//new webpack.optimize.CommonsChunkPlugin('common-bundle.js'),
//new webpack.optimize.CommonsChunkPlugin('public-bundle.js')
]
};
This is my styles.css
#div {
background-color: red;
}
The output I get from running my grunt task to run 'webpack' attached:
You can see where it says the build failed for the CSS.
cjs require fbjs/lib/mapObject [154] ./~/react/lib/ReactDOMFactories.js 18:16-45
[157] ./~/react/lib/onlyChild.js 1.21 kB {0} [built]
cjs require ./onlyChild [153] ./~/react/lib/ReactIsomorphic.js 24:16-38
[158] ./~/react/lib/deprecated.js 1.77 kB {0} [built]
cjs require ./deprecated [3] ./~/react/lib/React.js 19:17-40
[159] ./~/react-dom/index.js 63 bytes {0} [built]
cjs require react-dom [0] ./app/frontend/javascripts/entry.js 11:16-36
ERROR in ./app/frontend/javascripts/styles.css
Module parse failed: /Users/Booboo/Projects/Xeon/app/frontend/javascripts/styles.css Line 1: Unexpected token {
You may need an appropriate loader to handle this file type.
| div {
| background-color: red;
| }
# ./app/frontend/javascripts/entry.js 5:0-23
Warning: Task "webpack:dev" failed. Use --force to continue.
Aborted due to warnings.
Booboo$ grunt react && grunt webpack && grunt watch
I encounter this problem too.
But in my case, I found my loader was written as
{test: '/\.css$/', loader: 'style!css'}
which should be correctly written as
{test: /\.css$/, loader: 'style!css'}
note the '' around the /.css$/
I wise this would be helpful for you.
When you say
import styles from './styles.css';
you're trying to import a module that's not being exported as a module.
Try
import './styles.css';
instead to make it a simple file import.

Categories