I've been trying to run electron js with a react view layer. Both have different webpack configs. While the electron seems to be working fine, the react portion throws error.
Webpack config
let rendererConfig = {
entry: {
index: path.join(__dirname, '../src/render/index.js')
},
module: {
rules: [
{
test:/\.css$/,
use:['style-loader','css-loader']
},
{
test: /\.js?$/,
loader: 'babel-loader',
exclude: /node_modules/,
}
]
},
plugins: [
new HtmlWebpackPlugin({
title: 'BSK',
filename: 'index.html',
chunks: ['index'],
template: path.resolve(__dirname, '../src/render/index.html'),
nodeModules: devMode
? path.resolve(__dirname, '../node_modules')
: false
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin()
],
output: {
filename: '[name].js',
libraryTarget: 'commonjs2',
path: path.join(__dirname, '../dist/electron'),
globalObject: 'this'
},
target: 'electron-renderer',
}
This is my .babelrc
{
"env": {
"main": {
"presets": ["#babel/preset-env"]
},
"renderer": {
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": ["react-hot-loader/babel","#babel/plugin-proposal-class-properties","emotion"]
}
},
"plugins": [
"#babel/plugin-proposal-class-properties",
"#babel/plugin-transform-runtime"
]
}
I have all the required dev dependencies, but still the babel loader seems to be ignoring the presets
Adding '/' to publicPath of output fixed the issue
reference
Related
Building TS/SASS with Webpack works fine, running this through VSCode Live Server plugin renders the index.html perfectly to the app folder.
Running webpack-dev-server with it looking at the same app folder does not. The page opens but there is a Javascript error Uncaught SyntaxError: Unexpected token '<'
And the page does not render the JS/CSS.
webpack.config.js
// Imports
var path = require("path");
// Plugins
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
// Exports
module.exports = {
mode: 'development',
entry: './src/main.ts',
devtool: "inline-source-map",
resolve: {
extensions: [".ts", ".tsx", ".js"]
},
output: {
filename: 'main.min.js',
path: path.resolve(__dirname, 'app')
},
devServer: {
open: 'http://localhost',
port: 80,
publicPath: path.resolve(__dirname, 'app'),
hot: true
},
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
options: { minimize: true }
}
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
},
{
test: /\.scss$/,
use: [
"style-loader",
"css-loader",
"sass-loader"
]
},
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
}),
]
}
tsconfig.json
{
"compilerOptions": {
"sourceMap": true
}
}
main.ts
console.log('Main.ts has loaded')
import './styles/main.scss'
Any help with this would be appreciated, I'm losing my mind lol.
My issue was with syntax in the webpack.config.js file.
I was neglecting to insert a comma at the end of the last entry in every object and array, believing it not to be necessary.
Here is a working config:
// Imports
var path = require("path");
// Plugins
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
// Exports
module.exports = {
mode: 'development',
entry: './src/main.ts',
devtool: "inline-source-map",
output: {
filename: 'main.min.js',
path: path.resolve(__dirname, 'app'),
},
devServer: {
open: 'http://localhost',
port: 80,
},
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
options: { minimize: true },
}
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader',
]
},
{
test: /\.scss$/,
use: [
"style-loader",
"css-loader",
"sass-loader",
]
},
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html",
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css",
}),
]
}
I really appreciate some help here, in this case, I would Like to separate my vendor.js and my main.js at the final build operation.
I've tried that before to loop through in my package.json devDependency for separate my third party libraries and put it into vendor.js, it is working correctly but it produces vendor.js that is unnecessary in building process since my third library already is in my main.js
here is my weppack.config.js
var config = {
devtool: 'eval-source-map',
cache: true,
entry: {
main: path.join(__dirname, "app", "App.js"),
},
output: {
path: path.join(__dirname, 'scripts', 'js'),
filename: '[name].js',
chunkFilename: '[name].js',
sourceMapFilename: '[file].map',
publicPath: '/scripts/js/'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
['es2015', { modules: false }],
'react',
],
plugins: [
'syntax-dynamic-import',
'transform-object-rest-spread',
'transform-class-properties',
'transform-object-assign',
],
}
},
},
],
},
resolve: {
extensions: ['.js', '.jsx' ,'.css', '.ts'],
alias: {
'react-loadable': path.resolve(__dirname, 'app/app.js'),
},
},
};
Due to this answer
in his webpack.config.js (Version 1,2,3) file, He has
function isExternal(module) {
var context = module.context;
if (typeof context !== 'string') {
return false;
}
return context.indexOf('node_modules') !== -1;
}
in his plugins array
plugins: [
new CommonsChunkPlugin({
name: 'vendors',
minChunks: function(module) {
return isExternal(module);
}
}),
// Other plugins
]
This should solve your problem like mine.
I'm running into an interesting error with my react build. My configuration runs perfectly fine on my Mac, but I get the following error when running on my Windows 10 computer:
ERROR in ./~/react-toolbox/lib/app_bar/theme.css
Module parse failed: C:\cygwin64\home\username\projectname\node_modules\react-toolbox\lib\app_bar\theme.css Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
| :root {
| --palette-red-50: rgb(255, 235, 238 );
| --palette-red-100: rgb(255, 205, 210);
# ./~/react-toolbox/lib/app_bar/index.js 16:13-35
# ./src/containers/app/app.js
# ./src/index.js
# multi react-hot-loader/patch ./src/index.js
Here's my Webpack 2 Config
'use strict'
const webpack = require('webpack')
const path = require('path')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const postcssImport = require('postcss-import')
const postcssCssnext = require('postcss-cssnext')
// configure source and distribution folder paths
const publicFolder = 'public'
const buildFolder = 'build'
module.exports = {
entry: {
'app': [
'react-hot-loader/patch',
'./src/index.js'
]
},
resolve: {
//Allows us to leave off the file extension when importing
extensions: ['.js', '.json', '.jsx']
},
module: {
rules: [
{
enforce: 'pre',
test: /\.js$/,
exclude: '/node_modules/',
loader: 'eslint-loader',
},
{
test: /\.(js|jsx)$/,
exclude: '/node_modules/',
loader: 'babel-loader'
},
{
test: /\.css$/,
include: [
/(node_modules)\/react-toolbox/,
path.join(__dirname, 'src')
],
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
modules: true,
sourceMap: true,
importLoaders: 1
}
},
{
loader: 'postcss-loader',
options: {
sourceMap: 'inline',
plugins: function() {
return [
postcssImport({ addDependencyTo: webpack }),
postcssCssnext({
browsers: ['last 2 versions', '> 5%'],
compress: true,
})
]
},
},
}
]
})
}
]
},
plugins: [
new ExtractTextPlugin({
filename: '[name].bundle.css',
allChunks: true
}),
new CopyWebpackPlugin([{
from: path.join(__dirname, publicFolder, 'index.html'),
to: path.join(__dirname, buildFolder, 'index.html')
}]),
new CopyWebpackPlugin([{
from: path.join(__dirname, publicFolder, 'demo.html'),
to: path.join(__dirname, buildFolder, 'demo.html')
}]),
new CopyWebpackPlugin([{
from: path.join(__dirname, publicFolder, 'demo.js'),
to: path.join(__dirname, buildFolder, 'demo.js')
}]),
new webpack.NamedModulesPlugin()
],
output: {
path: path.resolve(__dirname, buildFolder),
filename: '[name].js',
publicPath: '/'
},
devtool: 'eval',
devServer: {
// files are served from this folder
contentBase: path.join(__dirname, 'build'),
// support HTML5 History API for react router
historyApiFallback: true,
// listen to port 5000, change this to another port if another server
// is already listening on this port
port: 5000,
//match the output 'publicPath'
publicPath: '/',
//Proxies to match requests to our Django API endpoints
proxy: {
'/api': {
target: 'http://localhost:4000'
}
},
hot: true
}
}
And for good measure, here's my .babelrc config
{
"presets": [
[ "es2015", { "modules": false } ],
"latest",
"react"
],
"plugins": ["react-hot-loader/babel", "syntax-dynamic-import"],
"env": {
"test": {
"plugins": ["dynamic-import-node"]
}
}
}
No idea why the error occurs when compiling on Windows 10 but works perfectly on my Mac. I can't seem to find any current info regarding this issue for either PostCSS or Webpack 2.
Any ideas?
just remove
include: [
/(node_modules)\/react-toolbox/,
path.join(__dirname, 'src')
]
from test: /\.css$/ rule
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.
Server rendered html does not contain any css. Only when react runs on client side, the css gets applied. What am i doing wrong?
Webpack config server + client: (shortened for brevity)
module.exports = [
{
name: "simple-server",
entry: [path.join(__dirname, "..", "src", "server.js")],
output: {
path: path.join(__dirname, "..", "build"),
filename: "server.js",
libraryTarget: "commonjs2",
},
target: "node",
externals: [nodeExternals()],
module: {
loaders: [
{
test: /\.scss$/,
loaders: ["css", "sass"],
},
{
test: /\.css$/,
loader: ["css"],
}
],
},
resolve: {
extensions: ["", ".js", ".jsx", ".scss"],
modulesDirectories: [ "src", "node_modules"],
},
},
{
name: "simple-client",
context: path.join(__dirname, "..", "src"),
entry: {
app: ["handlers/App", "webpack-hot-middleware/client?path=__webpack_hmr"],
},
devtool: "cheap-module-inline-source-map",
output: {
path: path.join(__dirname, "..", "build", "assets"),
filename: "[name].js",
publicPath: "assets/",
},
target: "web",
module: {
loaders: [
{
test: /\.scss$/,
loaders: ["style-loader","css-loader?sourceMap","postcss-loader","sass-loader?sourceMap"],
},
{
test: /\.css$/,
loaders: ["style-loader","css-loader?sourceMap","postcss-loader"],
}
],
},
postcss: () => [autoprefixer({ browsers: ["last 5 versions", "> 5%"] })],
resolve: {
extensions: ["", ".js", ".jsx", ".scss"],
modulesDirectories: [
"src",
"node_modules",
],
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new HtmlWebpackPlugin({
filename: "app.html",
template: "templates/main.html",
})
new webpack.HotModuleReplacementPlugin(),
],
},
];
Sample component :
import React from "react";
import "Styles.scss";
export default Component extends .... {}
You can tell webpack to create separate bundle for css when it creates js bundle. And use them in html head
<link rel="stylesheet" type="text/css" href="/static/style.css">
(There are many articles which suggest that it is better to have css in the head of html).
How to instruct webpack to separate css:
https://webpack.github.io/docs/stylesheets.html#separate-css-bundle
In short:
You have to install :
npm install extract-text-webpack-plugin --save
Add this plugin to plugin list:
plugins: [
new ExtractTextPlugin("style.css")
]
And in loaders:
{
test: /\.css$/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader")
},
{
test: /\.sass$/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader!sass-loader")
}
Im not sure if this works correctly with hmr (reloading css) because when I work with hmr Im not need server side rendering.
I have two webpack configs : dev and production. dev config use hmr and doesn't separate css (one bundle) and doesn't render server side. And production doesn't use hmr, have separated css and js and server side rendering.
You could check my configuration:
https://github.com/uhlryk/my-express-react-seed