Webpack doesn't correctly load my files - reactjs

I'm totally new to webpack and I'm doing my first configuration for a new project.
I'm trying to load my jsx/scss file but I've this problem:
var path = require('path');
var webpack = require('webpack');
var autoprefixer = require('autoprefixer');
var node_modules_dir = path.resolve(__dirname, 'node_modules');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var HtmlWebpackPlugin = require('html-webpack-plugin');
var cssExtractTextPlugin = new ExtractTextPlugin("css", "index.css");
var staticPrefix = path.join(__dirname, 'src')
var distPath = path.join(__dirname, 'dist')
module.exports = {
devtool: 'eval',
//context: path.join(__dirname, staticPrefix),
entry: {
'app': ['webpack-hot-middleware/client', path.join(__dirname, 'src/app.jsx')],
'vendor': [
'bootstrap/js/dropdown',
'bootstrap/js/tab',
'bootstrap/js/tooltip',
'bootstrap/js/alert',
'jquery',
'react-router',
'react-bootstrap'
],
'myapp': path.join(__dirname, 'src/stylesheets/base.scss') //'stylesheets/base.scss'
},
output: {
path: distPath,
filename: '[name].js',
libraryTarget: 'var',
library: 'exports',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.js'),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
'root.jQuery': 'jquery'
}),
new ExtractTextPlugin('[name].css')
],
module: {
loaders: [
{
test: /\.js$/,
loader: ['babel'],
include: path.join(__dirname, staticPrefix),
exclude: /(vendor|node_modules)/
},
{
test: /\.jsx$/,
loader: ['babel'],
include: path.join(__dirname, staticPrefix),
exclude: /(vendor|node_modules)/
},
{
test: /\.scss$/,
include: path.join(__dirname, staticPrefix),
loader: ExtractTextPlugin.extract('style-loader', 'css-loader!sass-loader-loader')
},
{
test: /\.(woff|woff2|ttf|eot|svg|png|gif|ico|jpg)($|\?)/,
loader: 'file-loader?name=' + '[name].[ext]'
}
]
},
postcss: function() {
return [autoprefixer];
},
resolve: {
modulesDirectories: [path.join(__dirname, staticPrefix), 'node_modules'],
extensions: ['', '.jsx', '.js']
},
};
The problem is that when I run: node_modules/.bin/webpack --config=webpack.config.dev it give me 2 errors:
ERROR in ./src/app.jsx
Module parse failed: /Users/work/Desktop/myapp-client/src/app.jsx Line 1: Unexpected token
You may need an appropriate loader to handle this file type.
| import React from 'react';
| console.log('hello!’);
|
# multi app
ERROR in ./src/stylesheets/base.scss
Module parse failed: /Users/work/Desktop/myapp-client/src/stylesheets/base.scss Line 1: Unexpected token {
You may need an appropriate loader to handle this file type.
| body {
| background: black;
| }
Where I'm doing wrong ?

With babel 6 you need to include the babel react preset to transpile your .jsx files. You also need to add the babel es2015 preset to transpile ES2015, i.e. ES6, syntax:
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules)/,
loader: 'babel',
query: {
presets:[ 'react', 'es2015' ]
}
}
]
}
On a side note, if you tweak your regex in the test key, you don't need two loader entries (for the .js and .jsx files).
Make sure you install these presets separately:
npm i -D babel-preset-es2015 babel-preset-react
More info on the babel 6 changes can be found here

Related

ts-loader with sass-loader & ExtractTextPlugin

This topic could be considered as a continuation of my previous question related to webpack & ts-loader
Now I am trying to understand how to use sass-loader with ts-loader and ExtractTextPlugin. After hours of digging it seems that ExtractTextPlugin is parsing node_modules and hence fails.
In the code example below you can see the commented part (the old style loader part) and new one which I'm trying to make work with guidance from sass-loader docs.
Currently I am stuck on this (and dozens of other similar parsing issues from node_modules):
webpack.config.js
const path = require('path');
const ExtractTextPlugin = require("extract-text-webpack-plugin"); // <-- as soon as this is imported, the build fails
const extractSass = new ExtractTextPlugin({
filename: "[name].[contenthash].css",
disable: process.env.NODE_ENV === "development"
});
module.exports = env => {
return {
devtool: "inline-source-map",
entry: "./src/index.tsx",
output: {
path: path.resolve(__dirname, "/public"),
filename: "build/app.js"
},
resolve: {
extensions: [".ts", ".tsx", ".js", ".json", ".scss"],
},
module: {
rules: [
{
test: /\.tsx?$/,
exclude: path.resolve(__dirname, "/node_modules"),
loader: "ts-loader",
},
{
test: /\.scss$/,
exclude: path.resolve(__dirname, "/node_modules"),
use: extractSass.extract({
use: [
{
loader: "style-loader",
exclude: path.resolve(__dirname, "/node_modules")},
{
loader: "css-loader",
exclude: path.resolve(__dirname, "/node_modules")},
{
loader: "sass-loader",
exclude: path.resolve(__dirname, "/node_modules"),
options: {
includePaths: [path.resolve(__dirname, "/src")],
}
},
],
}),
}
// {
// test: /\.scss$/,
// loader: 'style-loader!css-loader!sass-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
// }
],
},
plugins: [
extractSass,
]
}
}
N.B. Without ExtractTextPlugin I get an empty object when importing .scss into a .tsx file. So if you can help me solve also this issue, I would be glad (and able to continue coding) :)
import * as styles from "./Main.scss"; // <-- styles is {/* empty object */}

Webpack ReactJS file creation

I am trying out ReactJS with Webpack, hot updating, and React-Router. Below is my
webpack.config.js code. For some reason there are a bunch of json files being created at the very top of the file tree. For example, fb43026df6c9e1823c07.hot-update.json
Files end with .hot-update.json
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: [
'webpack-dev-server/client?http://localhost:5000',
'webpack/hot/dev-server',
'./scripts/index'
],
output: {
path: __dirname,
filename: 'bundle.js',
publicPath: '/static/'
},
resolve: {
extensions: ['', '.js']
},
devtool: 'eval-source-map',
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['babel-loader']
},
{
test: /\.scss$/,
loaders: ["style", "css", "sass"]
},
{
test: /\.jsx?$/,
loaders: ['babel'],
include: path.join(__dirname, 'scripts')
}
]
}
};
This is the file that Webpack's hotModuleReplacementPlugin is reading from every time you make a change and save it. It's making new bundles of your app for your front end to receive.

React-fetch requires react-addons, but there is no react/addons folder

Edit: The author has patched it.
I'm beginning to use react-fetch (well, trying to), and when trying to run webpack, I got this error :
ERROR in ./~/react-fetch/build/react-fetch.js
Module not found: Error: Cannot resolve 'file' or 'directory' E:\Users\Adrien\Documents\GitHub\brigad-admin-frontend/node_modules/react/addons in E:\Users\Adrien\Documents\GitHub\brigad-admin-frontend\node_modules\react-fetch\build
# ./~/react-fetch/build/react-fetch.js 17:19-42
But, as the error says, I have no react/addons folder (I'm using React 15.0.1).
Does anybody have had this issue before?
Thanks in advance.
PS: Here's my webpack.config.js:
const webpack = require('webpack');
const path = require('path');
const nodeDir = `${__dirname}/node_modules`;
const config = {
resolve: {
alias: {
react: `${nodeDir}/react`,
'react-dom': `${nodeDir}/react-dom`,
'react-router': `${nodeDir}/react-router`,
'react-fetch': `${nodeDir}/react-fetch`,
'react-bootstrap': `${nodeDir}/react-bootstrap`,
velocity: `${nodeDir}/velocity-animate`,
moment: `${nodeDir}/moment`,
slimscroll: `${nodeDir}/slimscroll`,
},
},
entry: {
routes: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./public/src/routes/js/main',
],
vendors: [
'react', 'react-dom', 'react-router', 'react-fetch', 'react-bootstrap',
'velocity', 'moment', 'slimscroll',
],
// chartVendors: ['raphael', 'morris'],
},
output: {
path: path.join(__dirname, 'public/dist'),
// publicPath: path.join(__dirname, 'public/dist/'),
filename: 'bundles/[name].bundle.js',
chunkFilename: 'chunks/[name].chunk.js',
},
module: {
loaders: [
{
test: /\.jsx?$/,
include: path.join(__dirname, 'public'),
loader: 'react-hot',
},
{
test: /\.js$/,
include: path.resolve(__dirname, 'public'),
loader: 'babel',
},
{
test: /\.css$/,
include: path.join(__dirname, 'public'),
loader: 'style!css-loader?modules&importLoaders=1' +
'&localIdentName=[name]__[local]___[hash:base64:5]',
},
],
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.optimize.CommonsChunkPlugin('vendors', './bundles/vendors.js', Infinity),
],
};
module.exports = config;
React API has changed. import React from 'react/addons' isn't valid in the current version. I can see the author uses React.addons.cloneWithProps from there.
The documentation suggests using React.cloneElement instead.
You could tweak the code accordingly and submit a PR to get this fixed.

CSS loading throw error using webpack

I have implemented webpack config like
/* eslint-disable no-var */
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: [
'webpack-hot-middleware/client',
'./src/main'
],
devtool: 'eval-source-map',
output: {
path: __dirname,
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel'],
include: path.join(__dirname, 'src')
},
{
test: /\.css$/, // Only .css files
loader: 'style!css' // Run both loaders
}
]
}
};
and I have installed the css-loader style-loader for loding the css on my page and I am using the bootstrap.min.css as below
require('../../node_modules/bootstrap/dist/css/bootstrap.min.css');
it's throw error like
Bootstrap is using the Glyphicons font. You also need to have a loader for the font:
{
test: /\.woff$/,
loader: 'url?limit=100000'
}
Source: christianalfoni.github.io/react-webpack-cookbook/Inlining-fonts
Or:
{
test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
loader: 'file-loader'
}
Source: stackoverflow.com/a/31183889/2378031

How to get sourcemaps working for React Css Modules?

I'm trying to setup a React project with react-css-modules, webpack and Hot Module Replacement. Everything is working like a charm but I can't get the CSS sourcemaps to work.
I followed this guide to make HMR work. It involves a BrowserSync setup to update the css file after Webpack writes it to disk.
I use (as suggested by react-css-modules) the ExtractTextPlugin to extract all of the css:
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style','css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!sass')
}
But if I change this to sourcemaps, as suggested here
loader: ExtractTextPlugin.extract('style', 'css?sourceMap!sass-loader outputStyle=expanded&sourceMap=true&sourceMapContents=true')
I get the error: "root" CSS module is undefined. in my browser console.
You can find my example repo here, but here's the full webpack config I'm using for development.
var webpack = require('webpack');
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var WriteFilePlugin = require('write-file-webpack-plugin').default;
module.exports = {
entry: {
bundle: [
'webpack/hot/dev-server',
'webpack-hot-middleware/client',
'./index.js'
]
},
devtool: 'cheap-module-source-map',
debug: true,
devServer: devServer,
context: path.resolve(__dirname, './src'),
output: {
path: path.resolve(__dirname, './builds'),
filename: '[name].js',
publicPath: '/builds/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.OldWatchingPlugin(),
new WriteFilePlugin(),
new ExtractTextPlugin('[name].css', {
allChunks: true
})
],
module: {
loaders: [
{
test: /\.js$/,
loaders: ['react-hot', 'babel-loader'],
exclude: /node_modules/
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style','css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!sass')
}
]
},
resolve: {
extensions: ['', '.js', '.json']
}
};
How to make the sourcemap work?
Use this:
ExtractTextPlugin.extract('style','css?sourceMap&modules&importLoaders=1&localI‌​dentName=[name]__[local]___[hash:base64:5]!sass?sourceMap')
i.e. add the sourceMap param to both css & sass loaders. It said so in sass-loader docs.
This is how I have my css modules set up:
'css-loader?modules&sourceMap&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!',

Resources