Im trying to get my images to appear in my build version of my react code.
```import reportIcon from "../../../../../src/img/reportmanager.svg";
<img src={reportIcon } className="img-icons-list" />```
this code works when I am in build version. My reportmanager icon shows up, but when I navigate to www.mywebsite.com/reports/user -- the icon disappears
import reportIcon from "/src/img/reportmanager.svg";
does not work either. here is my webpack.config.js file
```const HtmlWebPackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
var path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname + '/public'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env',
'#babel/react', {
'plugins': ['#babel/plugin-proposal-class-properties']
}]
},
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
},
{
test: /\.(eot|ttf|woff|woff2)$/,
loader: 'file-loader?name=./font/[name]_[hash:7].[ext]'
},
{
test: /\.(jpg|png|svg)$/,
loader: 'file-loader?name=./img/[name]_[hash:7].[ext]'
}
]
},
devServer: {
historyApiFallback: {
index: "/",
}
},
plugins: [
new ExtractTextPlugin("css/style.css"),
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
}),
function () {
this.plugin("done", function (stats) {
if (stats.compilation.errors && stats.compilation.errors.length && process.argv.indexOf('--watch') == -1) {
console.log(stats.compilation.errors);
process.exit(1); // or throw new Error('webpack build failed.');
}
// ...
});
}
]
};
I needed to put
<base href="/">
in the index.html of my react project.
Related
I want to be able to import a SASS file in a React component relative to the project's root directory, as opposed to having to do it relative to the component.
I want to be able to do the following in the componenet:
import styles from "styles/popup.sass"
as opposed to
import styles from "../../styles/popup.sass"
I used the resolve options in order to be able to do this and it works for other file types (i.e. .js and .png), but it does not work for .sass files. I get the following error:
Cannot find module 'styles/popup.sass'
I'm not sure why this isn't working for SASS files and would really appreciate any help.
Project Structure:
src
- js
- popup
- greeting_componenet.jsx
- styles
- popus.sass
Webpack Config file
var webpack = require("webpack"),
path = require("path"),
fileSystem = require("fs"),
env = require("./utils/env"),
CleanWebpackPlugin = require("clean-webpack-plugin").CleanWebpackPlugin,
CopyWebpackPlugin = require("copy-webpack-plugin"),
HtmlWebpackPlugin = require("html-webpack-plugin"),
WriteFilePlugin = require("write-file-webpack-plugin");
// load the secrets
var alias = {};
var secretsPath = path.join(__dirname, ("secrets." + env.NODE_ENV + ".js"));
var fileExtensions = ["jpg", "jpeg", "png", "gif", "eot", "otf", "svg", "ttf", "woff", "woff2"];
if (fileSystem.existsSync(secretsPath)) {
alias["secrets"] = secretsPath;
}
var options = {
mode: process.env.NODE_ENV || "development",
entry: {
popup: path.join(__dirname, "src", "js", "popup.js"),
options: path.join(__dirname, "src", "js", "options.js"),
background: path.join(__dirname, "src", "js", "background.js")
},
output: {
path: path.join(__dirname, "build"),
filename: "[name].bundle.js"
},
module: {
rules: [
{
test: /\.css$/,
loader: "style-loader!css-loader",
include: [
path.join(__dirname, 'src'),
/node_modules\/(semantic-ui-css)/
],
},
{
test: /\.(scss|sass)$/i,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 1,
modules: {
localIdentName: "[path]___[name]__[local]___[hash:base64:5]",
},
}
},
{
loader: 'postcss-loader',
options: {
plugins: function() {
return [require('autoprefixer')]
}
}
},
'sass-loader'
],
exclude: /node_modules/
},
{
test: new RegExp('\.(' + fileExtensions.join('|') + ')$'),
loader: "file-loader?name=[name].[ext]",
include: [
path.join(__dirname, 'src'),
/node_modules\/(semantic-ui-css)/
],
},
{
test: /\.html$/,
loader: "html-loader",
exclude: /node_modules/
},
{
test: /\.(js|jsx)$/,
loader: "babel-loader",
exclude: /node_modules/
}
]
},
resolve: {
alias: alias,
extensions: fileExtensions.map(extension => ("." + extension)).concat([".jsx", ".js", ".css", ".sass"]),
modules: [
path.resolve(__dirname, 'src'),
'node_modules'
]
},
plugins: [
// clean the build folder
new CleanWebpackPlugin(),
// expose and write the allowed env vars on the compiled bundle
new webpack.EnvironmentPlugin(["NODE_ENV"]),
new CopyWebpackPlugin([{
from: "src/manifest.json",
transform: function (content, path) {
// generates the manifest file using the package.json informations
return Buffer.from(JSON.stringify({
description: process.env.npm_package_description,
version: process.env.npm_package_version,
...JSON.parse(content.toString())
}))
}
}]),
new HtmlWebpackPlugin({
template: path.join(__dirname, "src", "popup.html"),
filename: "popup.html",
chunks: ["popup"]
}),
new HtmlWebpackPlugin({
template: path.join(__dirname, "src", "options.html"),
filename: "options.html",
chunks: ["options"]
}),
new HtmlWebpackPlugin({
template: path.join(__dirname, "src", "background.html"),
filename: "background.html",
chunks: ["background"]
}),
new WriteFilePlugin()
]
};
if (env.NODE_ENV === "development") {
options.devtool = "cheap-module-eval-source-map";
}
module.exports = options;
You need to add aliases for styles.
Something like:
module.exports = {
//...
resolve: {
alias: {
styles: path.resolve(__dirname, 'src/styles/'),
js: path.resolve(__dirname, 'src/js/')
}
}
};
Can someone help me with the Issue in my React Website?
We have used react-loadable for chunks whenever we deploy it on production environment the website get stuck on the loading part. Below is the URL
URL WITH LOADABLE: http://fcastage.surge.sh/
Any help will be appreciated.
We have tried making the website using react loadabale and without react loadable. But to make the website fast and load in chunks we have to use loadable . The react loadable is working fine with Development Environment but its not working when I am switching to Production.
Below is the Config File for Production
const HtmlWebpackPlugin = require("html-webpack-plugin");
//const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const path = require("path")
const webpack = require('webpack');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const { ReactLoadablePlugin } = require('react-loadable/webpack')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
mode: "production",
entry: "./app/index.js",
output: {
path: path.resolve(__dirname, "./build"),
filename: '[name].bundle.js',
chunkFilename: '[name].js',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader")
},
{
test: /\.less$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: [
{
//because remove style-loader,my css can't work
loader: "css-loader",
options: {
importLoaders: 1,
modules: true,
localIdentName: "[local]"
} // translates CSS into CommonJS
},
{
loader: "less-loader" // compiles Sass to CSS
}
]
})
},
{
test: /\.(jpe?g|png|gif|svg|ico)$/i,
use: [
{
loader: "url-loader",
options: {
outputPath: "assets/",
limit: 10 * 1024
}
}
]
},
{
test: /\.(woff|woff2|eot|ttf)$/i,
use: [
{
loader: "url-loader",
options: {
outputPath: "assets/"
}
}
]
}
]
},
optimization : {
splitChunks: {
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10
}
}
}
// minimizer: [
// new UglifyJsPlugin({
// uglifyOptions: {
// compress: {
// unused: true,
// dead_code: true,
// warnings: false
// }
// },
// sourceMap: true
// }),
// ]
},
plugins: [
new HtmlWebpackPlugin({
template: "./app/index.html",
hash: true,
filename: "index.html"
}),
//for surge.sh
new HtmlWebpackPlugin({
template: "./app/index.html",
hash: true,
filename: "200.html"
}),
new CleanWebpackPlugin(),
new ExtractTextPlugin("main.css"),
new webpack.DefinePlugin( {'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
'process.env.DEBUG': JSON.stringify(process.env.DEBUG) } ),
new ReactLoadablePlugin({
filename: path.resolve(__dirname, "build/react-loadable.json")
})
],
};
I have the following jsx component:
import React, { Component } from 'react';
class App extends Component {
render () {
return (
<div className="app">
<h2>Welcome to React</h2>
</div>
)
}
}
export default App;
and my webpack file:
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
context: path.resolve(__dirname, './src'),
entry: {
app: './index.jsx'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, './dist/assets'),
publicPath: '/assets',
},
devServer: {
contentBase: path.resolve(__dirname, './src')
},
module: {
rules: [
{
test: /\.jsx$/,
exclude: [/node-modules/],
use: [
{
loader: "babel-loader",
options: { presets: ["es2015"] }
}
]
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
use: [{
loader: 'css-loader',
options: { importLoaders: 1 },
}],
}),
},
{
test: /\.(sass|scss)$/,
use: ["style-loader", "css-loader", "sass-loader"]
}
]
},
resolve: {
modules: [
path.resolve(__dirname, './src'),
'node_modules'
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'common'
}),
new ExtractTextPlugin({
filename: '[name].bundle.css',
allChunks: true
})
]
}
however when I run:
node_modules/.bin/webpack -d
I get the following error:
Add "babel-preset-react"
npm install babel-preset-react
and add "presets" option to babel-loader in your webpack.config.js
Here is an example webpack.config.js:
module: {
loaders: [{
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['react', 'es2015', 'stage-1']
}
}]
}
I am receiving the following error:
ERROR in ./common/app.css Module parse failed:
E:\universal-starter\common\app.css Unexpected token (1:5) You may
need an appropriate loader to handle this file type.
| body {
| background-color: orange;
| }
My App.js file:
import React from 'react';
require('./app.css');
const App = () => <div>Hello from React</div>;
export default App;
My webpack.config:
const webpack = require('webpack');
const path = require('path');
const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin');
const HTMLWebpackPlugin = require('html-webpack-plugin');
module.exports = {
devtool: 'inline-source-map',
entry: [
'react-hot-loader/patch',
'webpack-dev-server/client?http://localhost:3001',
'webpack/hot/only-dev-server',
'./client/index',
],
target: 'web',
module: {
rules: [
{
enforce: 'pre',
exclude: /node_modules/,
loader: 'eslint-loader',
options: {
emitWarning: true
},
test: /\.(js|jsx)$/
},
{
exclude: /node_modules/,
test: /\.js?$/,
use: ['babel-loader']},
// WHY IS THIS WRONG & CAUSING THE PROBLEM?!?!?!?!
// embed styles in styles folder
{
test: /\.css$/,
use: ExtractTextWebpackPlugin.extract({
fallback: 'style-loader',
use: ['css-loader']
})
},
// fonts
{
test: /\.(woff|woff2|eot|ttf|svg)$/,
exclude: /node_modules/,
loader: 'url-loader?limit=1024&name=fonts/[name].[ext]'
},
// examine img file size
{
test: /\.(jpe?g|png|svg|gif)$/,
use: [{
loader: 'url-loader',
options: {
limit: 40000,
name: 'images/[name].[hash].[ext]',
}
},
{
loader: 'image-webpack-loader',
}
]
}
],
},
plugins: [
new ExtractTextWebpackPlugin('./css/styles.css'),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new HTMLWebpackPlugin({
template: './client/template/index.html',
}),
new webpack.DefinePlugin({
'process.env': { BUILD_TARGET: JSON.stringify('client') },
}),
],
devServer: {
host: 'localhost',
port: 3001,
historyApiFallback: true,
hot: true,
},
output: {
path: path.join(__dirname, '.build'),
publicPath: 'http://localhost:3001/',
filename: 'client.js',
},
};
Very little help out there so far on Webpack 3.
Any ideas?
Thanks!!
Try this:
In your App.js file, replace require('./app.css'); for import './app.css'
I am trying to use css modules inside react, but it is not working.
The log of this code:
import React from 'react'
import styles from '../../css/test.css'
class Test extends React.Component {
render() {
console.log(styles)
return (
<div className={styles.app}>
<p>This text will be blue</p>
</div>
);
}
}
export default Test
returns Object {}
and the rendered code are tags with no class:
<div><p>This text will be blue</p></div>
The css code is available at site, here is my test.css:
.test p {
color: blue;
}
If I changed the div to have class='test', the color of p changes to blue
Here is my webpack.config.js
var path = require('path')
var webpack = require('webpack')
var HappyPack = require('happypack')
var BundleTracker = require('webpack-bundle-tracker')
var path = require('path')
var ExtractTextPlugin = require("extract-text-webpack-plugin")
function _path(p) {
return path.join(__dirname, p);
}
module.exports = {
context: __dirname,
entry: [
'./assets/js/index'
],
output: {
path: path.resolve('./assets/bundles/'),
filename: '[name].js'
},
devtool: 'inline-eval-cheap-source-map',
plugins: [
new BundleTracker({filename: './webpack-stats.json'}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
}),
new HappyPack({
id: 'jsx',
threads: 4,
loaders: ["babel-loader"]
}),
new ExtractTextPlugin("[name].css", { allChunks: true })
],
module: {
loaders: [
{
test: /\.css$/,
include: path.resolve(__dirname, './assets/css/'),
loader: ExtractTextPlugin.extract("style-loader", "css-loader!resolve-url-loader?modules=true&localIdentName=[name]__[local]___[hash:base64:5]")
},
{
test: /\.scss$/,
include: path.resolve(__dirname, './assets/css/'),
loader: ExtractTextPlugin.extract("style-loader", "css-loader!resolve-url-loader!sass-loader?modules=true&localIdentName=[name]__[local]___[hash:base64:5]")
},
{
test: /\.jsx?$/,
include: path.resolve(__dirname, './assets/js/'),
exclude: /node_modules/,
loaders: ["happypack/loader?id=jsx"]
},
{
test: /\.png$/,
loader: 'file-loader',
query: {
name: '/static/img/[name].[ext]'
}
}
]
},
resolve: {
modulesDirectories: ['node_modules'],
extensions: ['', '.js', '.jsx'],
alias: {
'inputmask' : _path('node_modules/jquery-mask-plugin/dist/jquery.mask')
},
}
}
Can anyone help me?
Thanks in advance.
Looks like your passing the css-loader params to the resolve-url-loader:
"css-loader!resolve-url-loader?modules=true&localIdentName=[name]__[local]___[hash:base64:5]"
Should be:
"css-loader?modules=true&localIdentName=[name]__[local]___[hash:base64:5]&importLoaders=1!resolve-url-loader"
A lot of time passed since this question, so my webpack was update many times with another technologies.
This webpack config is working:
...
module.exports = {
entry,
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/'
},
devtool:
process.env.NODE_ENV === 'production' ? 'source-map' : 'inline-source-map',
module: {
rules: [
{
test: /\.jsx?$/,
include: path.resolve(__dirname, './app/view/'),
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.pcss$/,
include: path.resolve(__dirname, './app/view/'),
use: [
{
loader: 'style-loader'
},
{
loader:
'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
},
{
loader: 'postcss-loader',
options: {
plugins: function() {
return [
require('postcss-import'),
require('postcss-mixins'),
require('postcss-cssnext')({
browsers: ['last 2 versions']
}),
require('postcss-nested'),
require('postcss-brand-colors')
];
}
}
}
],
exclude: /node_modules/
},
{
test: /\.(png|svg|jpg|webp)$/,
use: {
loader: 'file-loader'
}
}
]
},
resolve: {
extensions: ['.js', '.jsx'],
modules: [path.resolve(__dirname, 'node_modules')]
},
plugins
};
I guess that there is an issue with older versions at webpack with this line:
'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
Try importLoaders and importLoader
You can see my repo too.
In my specific case, I'm using official utility facebook/create-react-app. You have to run the following command to get access to the webpack configuration:
npm run eject
You will then need to edit config/webpack.config.js and set the css-loader modules option to true.
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules:true <-----
}),