Webpack 3 SVG load error - javascript

Not sure why I'm getting this error as webpack is setup the same as an older project.
ERROR in ./app/static/imgs/sketch.svg
Module parse failed: /Users/leongaban/projects/personal/CoinHover/coinhover.io/app/static/imgs/sketch.svg Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
| <?xml version="1.0" encoding="UTF-8"?>
| <svg width="400px" height="400px" viewBox="0 0 400 400" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
| <!-- Generator: Sketch 47 (45396) - http://www.bohemiancoding.com/sketch -->
# ./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./app/coinhover.scss 6:13780-13815
error Command failed with exit code 2.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
The _svg.scss file:
.close-x {
position: relative;
background-size: 400px 400px;
background-image: url('static/imgs/sketch.svg'), none;
}
.close-x {
width: 30px;
height: 30px;
background-position: -41px -2px;
cursor: pointer;
}
package.json
{
"name": "coinhover",
"version": "0.0.2",
"main": "index.js",
"author": "Leon Gaban",
"license": "MIT",
"scripts": {
"start": "webpack && webpack-dev-server",
"dev": "webpack-dev-server",
"build": "webpack -p",
"production": "webpack -p",
"test": "eslint app && jest",
"test:fix": "eslint --fix app"
},
"now": {
"name": "coinhover",
"engines": {
"node": "7.4.x"
},
"alias": "coinhover.io"
},
"jest": {
"moduleNameMapper": {},
"moduleFileExtensions": [
"js",
"jsx"
],
"moduleDirectories": [
"node_modules"
]
},
"dependencies": {
"axios": "^0.16.2",
"babel-runtime": "^6.23.0",
"chalk": "^2.1.0",
"prop-types": "^15.5.10",
"ramda": "^0.24.1",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-hot-loader": "^1.3.1",
"react-redux": "^5.0.5",
"react-router": "^4.1.2",
"react-router-dom": "^4.1.2",
"redux": "^3.7.2",
"redux-thunk": "^2.2.0",
"svg-loader": "^0.0.2"
},
"devDependencies": {
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-plugin-transform-async-to-generator": "^6.24.1",
"babel-plugin-transform-es2015-modules-commonjs": "^6.24.1",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-polyfill": "^6.23.0",
"babel-preset-env": "^1.6.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-react-hmre": "^1.1.1",
"babel-preset-stage-0": "^6.24.1",
"copy-webpack-plugin": "^4.0.1",
"css-loader": "^0.28.4",
"enzyme": "^2.9.1",
"enzyme-to-json": "^1.5.1",
"extract-text-webpack-plugin": "^3.0.0",
"html-webpack-plugin": "^2.29.0",
"jest": "^20.0.4",
"node-sass": "^4.5.3",
"react-test-renderer": "^15.6.1",
"redux-mock-store": "^1.2.3",
"sass-loader": "^6.0.6",
"style-loader": "^0.18.2",
"url-loader": "^0.5.9",
"webpack": "^3.3.0",
"webpack-dev-server": "^2.5.1"
}
}
webpack
import webpack from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import CopyWebpackPlugin from 'copy-webpack-plugin';
import path from 'path';
import chalk from 'chalk';
const coinhover = path.resolve(__dirname, 'coinhover');
const app = path.resolve(__dirname, 'app');
const log = console.log;
// https://gist.github.com/leongaban/dc92204454b3513e511645af98107775
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: `${__dirname}/app/index.html`,
filename: 'index.html',
inject: 'body'
});
const ExtractTextPluginConfig = new ExtractTextPlugin({
filename: 'coinhover.css',
disable: false,
allChunks: true
});
const CopyWebpackPluginConfig = new CopyWebpackPlugin([{ from: 'app/static', to: 'static' }]);
const PATHS = {
app,
build: coinhover
};
const LAUNCH_COMMAND = process.env.npm_lifecycle_event;
const isProduction = LAUNCH_COMMAND === 'production';
process.env.BABEL_ENV = LAUNCH_COMMAND;
const productionPlugin = new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
});
const base = {
entry: [
PATHS.app
],
output: {
path: PATHS.build,
filename: 'index_bundle.js'
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: ['babel-loader']
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader'],
publicPath: coinhover
})
}
],
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' },
{ test: /\.css$/, loader: 'style-loader!css-loader' },
{
test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)(\?.*$|$)/,
loader: 'url-loader?limit=100000'
}
]
},
resolve: { modules: [path.resolve(__dirname, 'node_modules'), 'node_modules'] }
// resolve: {
// modules: ['node_modules', path.resolve(__dirname, '/app')]
// }
};
const developmentConfig = {
devServer: {
publicPath: '',
contentBase: path.join(__dirname, 'dist'),
quiet: true,
inline: true,
compress: true,
stats: 'errors-only',
open: true
},
devtool: 'cheap-module-inline-source-map',
plugins: [
CopyWebpackPluginConfig,
ExtractTextPluginConfig,
HtmlWebpackPluginConfig
]
};
const productionConfig = {
devtool: 'cheap-module-source-map',
plugins: [
CopyWebpackPluginConfig,
ExtractTextPluginConfig,
HtmlWebpackPluginConfig,
productionPlugin
]
};
log(`${chalk.magenta('🤖 ')} ${chalk.italic.green('npm run:')} ${chalk.red(LAUNCH_COMMAND)}`);
export default Object.assign({}, base,
isProduction === true ? productionConfig : developmentConfig
);

I do not know if its equivocal in the version of Webpack you are using (I've been using 1.15.0), but Webpack has issues parsing certain <xml> tags and within the <svg> element there are sometimes xmls/xmlns attributes that Webpack has problems parsing. These are generally erroneous verbose leftovers from Illustrator or other SVG generating applications. I had a very similar if not identical error where Webpack prompted for a loader in the error screen.
I bet if you strip your "sketch.svg" document of the <xml> tag wrapper and possibly the xmlns attributes as well Webpack will compile successfully.
(Boo to the users who gripe about stackoverflow best practices and do not even attempt to help.)

Related

React webpackage webpack-obfuscator: Cannot find module 'object-assign'

I'am tryng to use a webpack-obfuscator inside a React project. I added the configuration in order to obfucate the source code, but not the imported librariers, but I get this error message while luncing the command to create the webpack:
npm run dev
webpack Cannot find module 'object-assign'
Below the configuration I have for this project:
package.json
{
"name": "xyz",
"version": "1.0.0",
"private": true,
"homepage": "/apps/",
"dependencies": {
"#date-io/date-fns": "^1.3.13",
"#date-io/moment": "^2.6.0",
"#fortawesome/fontawesome-svg-core": "^1.2.28",
"#fortawesome/free-solid-svg-icons": "^5.13.0",
"#fortawesome/react-fontawesome": "^0.1.9",
"#material-ui/core": "^4.8.2",
"#material-ui/icons": "^4.5.1",
"#material-ui/lab": "^4.0.0-alpha.39",
"#material-ui/pickers": "^3.2.10",
"apexcharts": "^3.28.1",
"babel-preset-es2015": "^6.24.1",
"crypto-browserify": "^3.12.0",
"crypto-random-string": "^4.0.0",
"cypress": "^9.1.1",
"date-fns": "^2.14.0",
"dayjs": "^1.8.28",
"fetch-retry": "^3.1.0",
"i18next": "^21.5.4",
"i18next-browser-languagedetector": "^6.1.2",
"i18next-http-backend": "^1.3.1",
"isomorphic-fetch": "^3.0.0",
"jwt-decode": "^3.1.2",
"moment": "^2.26.0",
"mui-datatables": "^2.15.0",
"multimatch": "^6.0.0",
"npm": "^7.16.0",
"process": "^0.11.10",
"prop-types": "^15.8.1",
"react": "^16.14.0",
"react-alert": "^7.0.3",
"react-apexcharts": "^1.3.9",
"react-async": "^10.0.0",
"react-avatar": "^3.9.0",
"react-custom-scrollbars": "^4.2.1",
"react-dom": "^16.14.0",
"react-filter-box": "^3.4.2",
"react-grid-layout": "^0.17.1",
"react-helmet": "^6.1.0",
"react-i18next": "^11.14.3",
"react-image-mapper": "0.0.15",
"react-lineto": "^3.2.1",
"react-native-svg": "^12.1.1",
"react-number-format": "^4.4.1",
"react-responsive-carousel": "^3.2.18",
"react-router-dom": "^5.1.2",
"react-scripts": "^4.0.3",
"react-split-pane": "^0.1.89",
"react-svg-pathline": "^0.5.0",
"react-youtube": "^7.11.2",
"recharts": "^1.8.5",
"stream": "^0.0.2",
"typescript": "^3.7.0-dev"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"dev": "webpack serve",
"production": "webpack --mode production"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#babel/core": "^7.19.0",
"#babel/preset-env": "^7.19.0",
"#babel/preset-react": "^7.18.6",
"babel-loader": "^8.2.5",
"clean-webpack-plugin": "^4.0.0",
"css-loader": "^6.7.1",
"csv-loader": "^3.0.5",
"file-loader": "^6.2.0",
"html-loader": "^4.1.0",
"html-webpack-plugin": "^5.5.0",
"interpolate-html-plugin": "^4.0.0",
"javascript-obfuscator": "^4.0.0",
"mini-css-extract-plugin": "^2.6.1",
"node-sass": "^7.0.1",
"object-assign": "^4.1.1",
"papaparse": "^5.3.2",
"sass-loader": "^13.0.2",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.10.1",
"webpack-obfuscator": "^3.5.1",
"xml-loader": "^1.2.1"
}
}
.babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
webpack.config.js
'use strict';
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const InterpolateHtmlPlugin = require("interpolate-html-plugin");
const WebpackObfuscator = require('webpack-obfuscator');
const webpack = require('webpack');
//const multimatch = require('multimatch');
const publicUrl = process.env.PUBLIC_URL;
module.exports = {
mode: "development",
entry: {
app: "./src/index.js"
},
devtool: 'source-map', //'eval',
devServer: {
static: {
directory: path.join(__dirname, 'public'),
staticOptions: {
index: false
}
},
liveReload: false,
compress: true,
port: 80,
open: true,
hot: false,
client: false,
historyApiFallback: false
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
publicPath: "/"
},
resolve: {
extensions: [".wasm", ".mjs", ".js", ".jsx", ".ts", ".tsx", ".json"], // ['*', '.js', '.jsx'],
alias: {
'#': path.resolve(__dirname, 'src') // shortcut to reference src folder from anywhere
},
fallback: {
crypto: require.resolve('crypto-browserify'),
assert: require.resolve('assert'),
console: require.resolve('console-browserify'),
constants: require.resolve('constants-browserify'),
domain: require.resolve('domain-browser'),
events: require.resolve('events'),
http: require.resolve('stream-http'),
https: require.resolve('https-browserify'),
os: require.resolve('os-browserify/browser'),
path: require.resolve('path-browserify'),
punycode: require.resolve('punycode'),
process: require.resolve('process/browser'),
querystring: require.resolve('querystring-es3'),
stream: require.resolve('stream-browserify'),
string_decoder: require.resolve('string_decoder'),
sys: require.resolve('util'),
timers: require.resolve('timers-browserify'),
tty: require.resolve('tty-browserify'),
url: require.resolve('url'),
vm: require.resolve('vm-browserify'),
zlib: require.resolve('browserify-zlib'),
isomorphic: require.resolve('isomorphic-fetch'),
log: false,
object_assign: require.resolve('object-assign'),
scheduler: require.resolve('scheduler')
}
},
module: {
rules: [
{ // config for es6 jsx
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{ // config for sass compilation
test: /\.scss$/,
use: [
{
loader: MiniCssExtractPlugin.loader
},
'css-loader',
{
loader: "sass-loader"
}
]
},
{
test: /\.css$/,
use: [
// [style-loader](/loaders/style-loader)
{ loader: 'style-loader' },
// [css-loader](/loaders/css-loader)
{
loader: 'css-loader',
options: {
modules: true
}
},
// [sass-loader](/loaders/sass-loader)
{ loader: 'sass-loader' }
]
},
{ // config for images
test: /\.(png|svg|jpg|jpeg|gif)$/,
type: 'asset/resource',
exclude: /node_modules/,
use: ['file-loader?name=[name].[ext]']
},
{ // config for fonts
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
{
loader: 'file-loader',
options: {
outputPath: 'fonts',
}
}
],
},
{
test: /\.html$/i,
loader: "html-loader",
},
{
test: /\.js$/,
exclude: [
//path.resolve(__dirname, 'content.js')
path.resolve(__dirname, 'node_modules/react/index.js')
],
enforce: 'post',
//exclude: /node_modules/,
use: {
loader: WebpackObfuscator.loader,
options: {
rotateStringArray: true
}
}
}
],
noParse: [require.resolve('typescript/lib/typescript.js')]
},
plugins: [
new WebpackObfuscator ({
rotateStringArray: true
}),
new webpack.ProvidePlugin({
process: 'process/browser',
}),
new HtmlWebpackPlugin({ // plugin for inserting scripts into html
template: path.resolve(__dirname, "public/index.html"),
inject: true,
PUBLIC_URL: publicUrl
}),
new MiniCssExtractPlugin({ // plugin for controlling how compiled css will be outputted and named
filename: "css/[name].css",
chunkFilename: "css/[id].css"
}),
new InterpolateHtmlPlugin({
PUBLIC_URL: ''
})
]
};
Can anybody help on this?
Thanks in advance
Try in your terminal
npm install object-assign

Webpack: How to rewrie URL in .css

For 3 days straight I am having a trouble to setup Webpack for staging purposes.
The goal is to rewrite url of assets in final .css file (frontend.css) like this:
Let's say that in .scss file I have:
background: url('/assets/image.png') (this works for dev and prod)
and in final outputted .css file for staging, I want it to be:
background: url('https://stage.domain.com/staging/project-name/assets/image.png')
I have script npm run stage, that build js. and .css only for staging puposes.
It creates stage dir on root with two files frontened-bundle.js and frontend.css. (see bottom of "Files structure" screenshot).
I tried to rewrite url with resolve-url-loader with root parameter, but I cant get it working.
publicPath is also ignored.
I am not sure what I am doing wrong.
Please point me in right direction.
Files structure:
webpack.stage.js:
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const StyleLintPlugin = require('stylelint-webpack-plugin');
const public_path = 'https://stage.domain.com/staging/project-name/'
module.exports = {
context: __dirname,
entry: {
frontend: [
'./src/js/index.js',
'./src/scss/main.scss'
],
// customizer: './src/customizer.js'
},
resolve: {
extensions: ['.ts', '.js', '.jsx', '.scss', '...',],
},
output: {
path: path.resolve(__dirname, 'stage'),
publicPath: public_path,
filename: '[name]-bundle.js'
},
mode: 'production',
// devtool: 'cheap-eval-source-map',
module: {
rules: [
{
enforce: 'pre',
exclude: /node_modules/,
test: /\.jsx$/,
loader: 'eslint-loader'
},
{
test: /\.jsx?$/,
loader: 'babel-loader'
},
{
test: /\.s?css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: public_path,
sourceMap: true
}
},
{
loader: 'css-loader',
options: {
url: false,
sourceMap: true
}
},
{
loader: 'resolve-url-loader',
options: {
// root: path.join(__dirname, './'), // returns url("../../assets/assets/fonts/NewYork.woff2")
// root: '/', // returns url('../../../../../../assets/fonts/NewYork.woff2')
// root: './', // returns url('../../assets/fonts/NewYork.woff2')
attempts: 1,
debug: true,
sourceMap: true,
publicPath: public_path,
},
},
{
loader: 'sass-loader',
options: {
sourceMap: true
}
},
]
},
{
test: /\.(ttf|woff|woff2|eot|jpe?g|png|svg|gif)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: [
{
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
// outputPath: '../',
publicPath: publicPath,
},
},
'img-loader',
'url-loader',
]
}
]
},
plugins: [
// new StyleLintPlugin(),
new MiniCssExtractPlugin({
filename: '[name].css'
}),
],
optimization: {
// minimizer: [new UglifyJsPlugin(), new OptimizeCssAssetsPlugin()]
}
};
package.json
{
"name": "project_name",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack --mode=production",
"dev": "webpack --watch",
"stage": "npm run clean && webpack --config webpack.stage.js -p --progress --profile",
"clean": "rm -rf stage"
},
"repository": {
"type": "git",
"url": ""
},
"keywords": [
"webpack"
],
"author": "",
"license": "ISC",
"bugs": {
"url": ""
},
"homepage": "",
"devDependencies": {
"#babel/cli": "^7.14.5",
"#babel/core": "^7.6.2",
"#babel/preset-env": "^7.6.2",
"autoprefixer": "^9.6.4",
"babel-eslint": "^10.0.3",
"babel-loader": "^8.0.6",
"browser-sync": "^2.27.4",
"browser-sync-webpack-plugin": "^2.2.2",
"css-loader": "^3.2.0",
"css-mqpacker": "^7.0.0",
"eslint": "^6.5.1",
"eslint-config-prettier": "^6.4.0",
"eslint-config-wordpress": "^2.0.0",
"eslint-loader": "^3.0.2",
"eslint-plugin-prettier": "^3.1.1",
"extract-text-webpack-plugin": "^3.0.2",
"file-loader": "^4.2.0",
"img-loader": "^3.0.1",
"mini-css-extract-plugin": "^0.8.0",
"node-sass": "^4.14.1",
"optimize-css-assets-webpack-plugin": "^5.0.3",
"postcss-loader": "^3.0.0",
"prettier": "^1.18.2",
"resolve-url-loader": "^4.0.0",
"sass-loader": "^8.0.0",
"style-loader": "^1.0.0",
"stylelint": "^11.0.0",
"stylelint-config-recommended-scss": "^4.0.0",
"stylelint-config-wordpress": "^15.0.0",
"stylelint-order": "^3.1.1",
"stylelint-scss": "^3.11.1",
"stylelint-webpack-plugin": "^1.0.1",
"svg-sprite-loader": "^4.1.6",
"svgo": "^1.3.0",
"svgo-loader": "^2.2.1",
"uglifyjs-webpack-plugin": "^2.2.0",
"url-loader": "^4.1.1",
"webpack": "^4.41.0",
"webpack-cli": "^3.3.9",
"wp-pot-cli": "^1.5.0"
},
"dependencies": {
"#babel/polyfill": "^7.6.0",
"imagemin": "^8.0.0",
"jquery": "^3.6.0"
}
}
I've had this similar issue in the past, I tried the below from the docs,
const ASSET_PATH = process.env.ASSET_PATH || '/';
export default {
output: {
publicPath: ASSET_PATH,
},
plugins: [
// This makes it possible for us to safely use env vars on our code
new webpack.DefinePlugin({
'process.env.ASSET_PATH': JSON.stringify(ASSET_PATH),
}),
],
};
But actually, the one that worked perfectly for my issue is below, while the public path was the CDN link from where the assets were served
require('dotenv').config();
__webpack_public_path__ = config.publicPath // publicPath is process.env.ASSET_PATH || '/';
When you set the publicPath as "../" did you also try the useRelativePaths: true?
Ref:- https://github.com/webpack-contrib/file-loader#userelativepath

Integrate React 17 with webpack 5 and babel-plugin-react-css-modules (css modules with stylename)

I am trying to setup a react app with latest versions.
React 17, Webpack 5 and other modules.
I need css modules with styleName concept by using babel-plugin-react-css-modules
Trying to run the code shows the output but no styles are applied.
package.json
{
"name": "react-app",
"version": "1.0.0",
"description": "React Template App",
"author": "",
"license": "ISC",
"main": "index.js",
"scripts": {
"start": "webpack serve --mode development",
"build": "webpack --mode production",
"format": "prettier --write \"src/**/*.js\"",
"eslint-fix": "eslint --fix \"src/**/*.js\""
},
"dependencies": {
"babel-plugin-react-css-modules": "^5.2.6",
"react": "^17.0.1",
"react-dom": "^17.0.1"
},
"devDependencies": {
"#babel/core": "^7.12.10",
"#babel/preset-env": "^7.12.11",
"#babel/preset-react": "^7.12.10",
"babel-eslint": "^10.1.0",
"babel-loader": "^8.2.2",
"css-loader": "^5.0.1",
"eslint": "^7.16.0",
"eslint-config-react": "^1.1.7",
"eslint-loader": "^4.0.2",
"eslint-plugin-react": "^7.21.5",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^4.5.0",
"less": "^4.0.0",
"less-loader": "^7.2.0",
"mini-css-extract-plugin": "^1.3.3",
"prettier": "2.2.1",
"style-loader": "^2.0.0",
"webpack": "^5.11.0",
"webpack-cli": "^4.2.0",
"webpack-dev-server": "^3.11.0"
}
}
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: __dirname + '/dist',
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: path.join(__dirname, "dist"),
open: true,
host: "localhost",
compress: true,
port: process.env.CLIENT_PORT,
hot: true,
quiet: false
},
module: {
rules: [{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader', 'eslint-loader']
},
{
test: /\.css$/,
use: [
'style-loader',
MiniCssExtractPlugin.loader,
// "less-loader",
{
loader: 'css-loader',
options: {
modules: true,
}
}
],
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ["file-loader"]
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: "./public/index.html",
filename: "./index.html",
favicon: "./public/favicon.ico"
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
],
devtool: 'inline-source-map',
};
.babelrc
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
[
"babel-plugin-react-css-modules",
{
"webpackHotModuleReloading": true,
"autoResolveMultipleImports": true
}
]
]
}
home.js
import React from "react";
import "./style.css";
const Home = () => {
return (
<div styleName="container">
<div styleName="title">Hello from Home CSS</div>
</div>
);
};
export default Home;
style.css
.container {
display: flex;
flex-direction: column;
}
.title {
font-size: 24px;
color: red;
}
That's interesting issue which requires us to do a few more things to make it work as following:
babel-plugin-react-css-modules isn't working properly with css-loader in case of generating the name. But luckily we have a work around by using a temporary fix of someone #dr.pogodin/babel-plugin-react-css-modules. So just install needed packages:
npm i -D #dr.pogodin/babel-plugin-react-css-modules postcss // postcss is required aslo
Reconfigure babel configuration by changing the name in .babelrc:
{
// ...
"plugins": [
[
"#dr.pogodin/babel-plugin-react-css-modules",
{
"webpackHotModuleReloading": true,
"autoResolveMultipleImports": true
}
]
]
}
Finally, we would change the class name to make it consistent between babel-plugin-react-css-modules and css-loader in webpack.config.js:
{
test: /\.css$/,
use: [
// ...
{
loader: 'css-loader',
options: {
modules: {
localIdentName: '[path]___[name]__[local]___[hash:base64:5]', // This pattern matches with the default in `babel-plugin-react-css-modules`
},
}
}
],
}

Webpack does not recognize ractive-loader

I have a project using ractivejs with webpack. I added the ractive-loader, which can be found here https://www.npmjs.com/package/ractive-loader
When I try to build the project using npm run build:dev, i get the following error message in template:
`ERROR in ./src/Templates/Feed/Main.html 1:2
Module parse failed: Unexpected character '#' (1:2)
You may need an appropriate loader to handle this file type.
> {{#Feeds}}
| {{title}}
| {{/Feeds}}`
Template: Main.html
`{{#Feeds}}
<h1>{{title}}</h1>
{{/Feeds}}`
My webpack looks like this:
webpack.config
`const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const {
prod_Path,
src_Path
} = require('./path');
const {
selectedPreprocessor
} = require('./loader');
module.exports = {
entry: {
main: './' + src_Path + '/main.js'
},
output: {
path: path.resolve(__dirname, prod_Path),
filename: '[name].[chunkhash].js'
},
devtool: 'source-map',
devServer: {
open: true,
},
module: {
rules: [{
test: /\.html$/,
use: {
loader: 'ractive-loader'
},
test: selectedPreprocessor.fileRegexp,
use: [{
loader: MiniCssExtractPlugin.loader,
},
{
loader: 'css-loader',
options: {
modules: false,
sourceMap: true
}
},
{
loader: 'postcss-loader',
options: {
sourceMap: true
}
},
{
loader: selectedPreprocessor.loaderName,
options: {
sourceMap: true
},
}
]
}]
},
plugins: [
new MiniCssExtractPlugin({
filename: 'style.css',
}),
new HtmlWebpackPlugin({
inject: false,
hash: false,
template: './' + src_Path + '/index.html',
filename: 'index.html'
})
],
resolve: {
alias: {
pubsub: 'aurelia-event-aggregator',
Ractive: 'ractive'
}
}
};`
Package.json
`{
"name": "project",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"build:dev": "webpack-dev-server --env dev --mode none",
"build:prod": "webpack --env prod --mode production",
"build:watch": "webpack-dev-server --env dev --mode none"
},
"author": "mwieth",
"license": "ISC",
"devDependencies": {
"autoprefixer": "^8.6.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"clean-webpack-plugin": "^0.1.19",
"css-loader": "^0.28.11",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.4.0",
"node-sass": "^4.11.0",
"postcss-loader": "^2.1.5",
"sass-loader": "^7.0.2",
"style-loader": "^0.21.0",
"webpack": "^4.10.2",
"webpack-cli": "^3.0.1",
"webpack-dev-server": "^3.1.14",
"webpack-md5-hash": "0.0.6",
"ractive": "^1.3.2",
"ractive-animatecss": "^0.1.0",
"ractive-datetime": "^1.0.0",
"ractive-loader": "^0.5.6",
"ractive-markdown": "^0.1.1",
"ractive-route": "github:martinkolarik/ractive-route",
"aurelia-event-aggregator": "^1.0.2",
"axios": "^0.18.0"
},
"dependencies": {
"acorn": "^6.1.1",
"normalize.css": "^8.0.1"
}
}`
from looking at the docs here
https://github.com/rstacruz/ractive-loader
the syntax for adding ractive-loader is just 'ractive' instead of 'ractive-loader'
use: {
test: /\.html$/,
loader: 'ractive'
}
altho it seems they do it a bit differently if you follow their example exactly
module: {
loaders: [
{ test: /\.html$/, loader: 'ractive' }
]
}

Webpack generates a bundle.min.js file per image

I have a React project with a lot of images and Webpack2 configuration. Whenever I build my project it generates one bundle file per image - which results in about 140 bundle.min.js files:
I've been searching like a fanatic to find out why or if there is a better way to do this (it would be wonderful if i could just have one file for all these - if possible?). Here is my code:
webpack.config.prod.js
// PRODUCTION
const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const entry = {
app: path.join(process.cwd(), 'src/app.js')
}
const output = {
path: path.join(__dirname, 'dist'),
filename: 'bundle.min.js',
}
const plugins = [
new webpack.DefinePlugin({
// 'process.env.NODE_ENV': JSON.stringify('production')
'process.env': {
NODE_ENV: JSON.stringify('production')
}
}),
new webpack.optimize.UglifyJsPlugin({
mangle: false,
compress: {
warnings: false
}
}),
new ExtractTextPlugin('bundle.css'), // creation of HTML files to serve your webpack bundles
new HtmlWebpackPlugin({
template: 'index-template.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'bundle',
filename: '[name].common.js'
})
]
const config = {
context: path.join(__dirname, 'src'),
entry: entry,
output: output,
devtool: "source-map",
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
include: path.join(__dirname, 'src'),
use: "babel-loader"
},
{
test: /\.(png|jpg|gif)$/,
use: [{
loader: 'url-loader',
options: { limit: 10000, name: './images/[name].[ext]' } // Convert images < 10k to base64 strings (all in images folder)
}]
},
{
test: /\.(sass|scss)$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
'css-loader',
{
loader: 'postcss-loader',
options: {
plugins: (loader) => [ require('autoprefixer')() ]
}
},
'sass-loader',
]
})
}
]
},
plugins: plugins,
externals: {
jquery: 'jQuery'
}
}
module.exports = config;
package.json
{
"name": "magdenmagden",
"version": "1.0.0",
"description": "A webbased art gallery",
"main": "index.js",
"author": "fransBernhard <mimilundberg#fransbernhard.se>",
"license": "ISC",
"scripts": {
"start": "NODE_ENV=development node dev-server.js --history-api-fallback",
"build": "rimraf dist && NODE_ENV=production webpack --config webpack.config.prod.js",
"test": "rimraf jest/__snapshots__ coverage && jest --no-cache --coverage"
},
"jest": {
"transform": {
"^.+\\.(js|jsx$)": "<rootDir>/node_modules/babel-jest",
"^.+\\.css$": "<rootDir>/jest/config/styleTransform.js",
"^.+\\.(jpg|jpeg|png|gif)$": "<rootDir>/jest/config/fileTransform.js"
},
"moduleFileExtensions": [
"js",
"jsx"
],
"moduleNameMapper": {
".*\\.scss$": "<rootDir>/jest/config/styleTransform.js"
}
},
"dependencies": {
"axios": "^0.16.2",
"backstopjs": "^2.7.5",
"react": "^15.5.4",
"react-dom": "^15.5.4"
},
"devDependencies": {
"babel-core": "^6.24.1",
"babel-eslint": "^7.2.3",
"babel-jest": "^20.0.3",
"babel-loader": "^7.0.0",
"babel-plugin-dynamic-import-node": "^1.0.2",
"babel-plugin-syntax-dynamic-import": "^6.18.0",
"babel-plugin-transform-es2015-modules-commonjs": "^6.24.1",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-react-hmre": "^1.1.1",
"babel-preset-stage-0": "^6.24.1",
"css-loader": "^0.28.2",
"eslint": "^3.19.0",
"eslint-config-react-app": "^1.0.4",
"eslint-loader": "^1.7.1",
"eslint-plugin-flowtype": "^2.34.0",
"eslint-plugin-import": "^2.3.0",
"eslint-plugin-jsx-a11y": "^5.0.3",
"eslint-plugin-react": "^7.0.1",
"extract-text-webpack-plugin": "^2.1.0",
"file-loader": "^0.11.1",
"html-webpack-plugin": "^2.28.0",
"jest": "^20.0.4",
"json-loader": "^0.5.4",
"node-sass": "^4.5.3",
"postcss-loader": "^2.0.5",
"prop-types": "^15.5.10",
"react-hot-loader": "^3.0.0-beta.7",
"react-modal": "^1.7.7",
"react-router": "^3.0.5",
"react-router-dom": "^4.1.1",
"react-scrollchor": "^3.0.0",
"react-test-renderer": "^15.5.4",
"rimraf": "^2.6.1",
"sass-loader": "^6.0.5",
"screener-storybook": "^0.7.10",
"style-loader": "^0.17.0",
"url-loader": "^0.5.8",
"webpack": "^2.5.1",
"webpack-dev-server": "^2.4.5"
}
}
So effing greatful for any input!

Categories