How to add multiple entry to reactjs project? - javascript

I was trying to configure webpack to have multiple entries in my reactjs project.
after running npm start the development server starts and opens a window but for some reason, the compilation stuck and does not continue.
and when I try to build the project an error shows:
Creating an optimized production build...
Failed to compile.
Cannot read properties of undefined (reading 'filter')
this is my project structure:
src folder
public folder
config:
paths.js :
appHtml: resolveApp('public/client/index.html'),
appIndexJs: resolveModule(resolveApp, 'src/client/index'),
adminHtml: resolveApp('public/admin/index.html'),
adminIndexJs: resolveModule(resolveApp, 'src/admin/index'),
webpack.config.js :
entry: {
client: paths.appIndexJs,
admin: paths.adminIndexJs,
},
output: {
path: paths.appBuild,
pathinfo: isEnvDevelopment,
filename: isEnvProduction
? 'static/js/[name].[contenthash:8].js'
: isEnvDevelopment && 'static/js/[name].bundle.js',
chunkFilename: isEnvProduction
? 'static/js/[name].[contenthash:8].chunk.js'
: isEnvDevelopment && 'static/js/[name].chunk.js',
assetModuleFilename: 'static/media/[name].[hash][ext]',
publicPath: paths.publicUrlOrPath,
devtoolModuleFilenameTemplate: isEnvProduction
? info =>
path
.relative(paths.appSrc, info.absoluteResourcePath)
.replace(/\\/g, '/')
: isEnvDevelopment &&
(info => path.resolve(info.absoluteResourcePath).replace(/\\/g, '/')),
},
plugins: [
new HtmlWebpackPlugin(
Object.assign(
{},
{
title: "admin",
hash: true,
inject: true,
filename: 'index.html',
template: paths.adminHtml,
}
)
),
new HtmlWebpackPlugin(
Object.assign(
{},
{
title: "client",
hash: true,
inject: true,
filename: 'index.html',
template: paths.appHtml,
}
)
),
]
webpackDevServer.config.js :
historyApiFallback: {
rewrites: [
{ from: /^\/client/, to: '/public/client/index.html' },
{ from: /^\/admin/, to: '/public/admin/index.html' },
],
}

Related

Multiple HtmlWebpackPlugins with webpack DevServer

You can use multiple HtmlWebpackPlugin plugins to create more than one HTML file in production, but only one of the HTML files will be used by the DevServer. Is there any way to use all the HtmlWebpackPlugin plugins in development as well?
module.exports = {
entry: {
main: './src/main.js',
anotherEntry: './src/anotherEntry.js'
},
// This only serves the index.html file on 404 responses
devServer: {
contentBase: './dist',
historyApiFallback: true,
port: 3000,
},
// ...
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/main.html',
chunks: ['main'],
}),
new HtmlWebpackPlugin({
filename: 'anotherEntry.html',
template: './src/anotherEntry.html',
chunks: ['anotherEntry'],
}),
]
};
historyApiFallback can be given manual rewrites to control in a more fine-grained manner what the DevServer should fallback to on 404 responses. This way we can serve the other files in development as well.
module.exports = {
entry: {
main: './src/main.js',
anotherEntry: './src/anotherEntry.js'
},
devServer: {
contentBase: './dist',
historyApiFallback: {
rewrites: [
{ from: /^\/anotherEntry/, to: '/anotherEntry.html' },
{ to: '/index.html' },
],
},
port: 3000,
},
// ...
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/main.html',
chunks: ['main'],
}),
new HtmlWebpackPlugin({
filename: 'anotherEntry.html',
template: './src/anotherEntry.html',
chunks: ['anotherEntry'],
}),
]
};

Public assets is 404 on prod build (webpack)

I'm not really familiar with webpack and I have this issue where I can't access my assets on prod - it returns 404
I have this structure:
- repo
- public
- index.html
- images
- animals
- dog.png
- audio
- growl.mp3
- src
- index.js
... other files
Now on my index.js (or other files) I access the images by doing:
import { Loader, utils, Sprite, AnimatedSprite } from 'pixi.js'
loader
.add('images/animals/dog.png' )
.load(async () => {})
... other codes
And this works fine on local, but when I deploy on production It throws
Failed to load resource: the server responded with a status of 404 () - /images/animals/dog.png:1 Failed to load resource: the server responded with
My webpack looks like this:
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const CircularDependencyPlugin = require('circular-dependency-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const isProd = process.env.NODE_ENV === 'production'
module.exports = {
mode: isProd ? 'production' : 'development',
entry: './src/index.js',
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'build'),
publicPath: '/',
},
resolve: {
modules: [path.resolve(__dirname, 'src'), 'node_modules'],
},
devtool: isProd ? 'cheap-module-eval-source-map' : 'source-map',
devServer: {
hot: true,
watchContentBase: true,
contentBase: [
path.resolve(__dirname, 'public'),
path.resolve(__dirname, 'build'),
],
publicPath: '/',
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
},
},
},
],
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: 'public/index.html',
}),
new CircularDependencyPlugin({
exclude: /a\.js|node_modules/,
failOnError: false,
cwd: process.cwd(),
}),
new CopyWebpackPlugin([
{ from: 'public/audio', to: 'audio' },
{ from: 'public/images', to: 'images' },
]),
],
}
Ok, so I figured it out.
It turns out that I just need to make all publicPath to '' (empty string)

Webpack Dev Server Not Hot Reloading .vue files

Been working on a project and was sure HMR was working, any of my .js files if I would update them webpack would compile and the module would be replaced all hot like.
I was working on a .vue file and webpack would recompile, but there was no super fresh HMR.
Hoping someone can take a look and tell me if something is off:
The script I'm using in the cli looks like this.
webpack-dev-server --d --watch --output-path ./public --config ./_src/webpack.config.js --progress --env.dev
I'm guessing the most important bit to look at is this:
devServer: {
contentBase: 'public',
hot: true,
filename: 'main.js',
overlay: true,
stats: { colors: true },
port: 3000,
proxy: {
'/': {
target: 'http://moment.local/',
secure: false,
changeOrigin: true
}
},
historyApiFallback: true
},
But here is my whole config if it helps.
const webpack = require('webpack')
const {resolve} = require('path')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
module.exports = env => {
const addPlugin = (add, plugin) => add ? plugin : undefined
const ifProd = plugin => addPlugin(env.prod, plugin)
const removeEmpty = array => array.filter(i => !!i)
// Our Sass Extraction Plugin
const extractSass = new ExtractTextPlugin({
filename: 'style.css',
disable: env.dev
})
return {
entry: {
'vendor': ['jquery', 'KlaviyoSubscribe', 'learnq', 'select2', 'slick-carousel', 'moment', 'lodash'],
'main': resolve(__dirname, './js/index.js')
},
output: {
filename: '[name].js',
path: resolve(__dirname, '../public/'),
pathinfo: !env.prod
},
module: {
loaders: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
css: 'vue-style-loader!css-loader!postcss-loader!sass-loader', // <style lang='scss'>
scss: 'vue-style-loader!css-loader!postcss-loader!sass-loader', // <style lang='scss'>
sass: 'vue-style-loader!css-loader!postcss-loader!sass-loader?indentedSyntax' // <style lang='sass'>
}
}
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{ test: /\.s(c|a)ss$/,
use: extractSass.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
importLoaders: 1,
sourceMap: true
}
},
'postcss-loader?sourceMap',
'sass-loader?sourceMap'
]
})
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}
]
},
devtool: env.prod ? 'source-map' : 'eval',
devServer: {
contentBase: 'public',
hot: true,
filename: 'main.js',
overlay: true,
stats: { colors: true },
port: 3000,
proxy: {
'/': {
target: 'http://moment.local/',
secure: false,
changeOrigin: true
}
},
historyApiFallback: true
},
bail: env.prod, // Fail out on the first error if production
resolve: {
alias: {
'vue$': 'vue/dist/vue.common.js'
}
},
plugins: removeEmpty([
extractSass,
new webpack.HotModuleReplacementPlugin(),
new webpack.optimize.CommonsChunkPlugin({
// Let's create js for our vendor scripts
name: 'vendor',
// (with more entries, this ensures that no other module
// goes into the vendor chunk)
minChunks: Infinity
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'commons',
filename: 'commons.js',
// (Modules must be shared between 2 entries)
minChunks: 2
})
...
])
}
}
Really struggling here so anything would be great.
It sounds like you want the "hot" behaviour but you are missing the --hot option in the script you posted. The documentation for that option is here.
You have a lot of options already; just add --hot and that should do the trick.
UPDATE:
I do see that you have the hot: true set in the devServer property of your webpack config, but if I don't use --hot in the cli, I get the following error in the console, so that is why I am saying to use it even though you would think it would be covered by the config - its not.
Uncaught Error: [HMR] Hot Module Replacement is disabled.
Add a file called vue.config.js in your root directory.
Inside it you can enable hot reloading via:
module.exports = {
devServer: {
watchOptions: {
poll: true
}
}
};
I used this settings in a project that was set up via vue create.

Webpack Multi Page Application Serving

I have one react project but I split to two part(admin,front). I want to serv this two part different port via one webpack devserver.
It is possible when I run "npm run start" , two part working at different ports
I built with webpack , outputs in dist directory here
admin.html
index.html
admin.js
index.js
common.js
If I open localhost:8081 -> must return index.html(includes index.js and common.js)
If I open localhost:8082 -> must return admin.html(includes admin.js,common.js)
webpack configuration :
entry: options.production ? {
interview: ["./app/src/pages/interview/main.js"],
admin: ["./app/src/pages/dashboard/main.js"]
} : {
interview: [
'webpack-dev-server/client?http://' + options.ip + ':8081',
"./app/src/pages/interview/main.js",
'webpack/hot/only-dev-server'],
admin: ['webpack-dev-server/client?http://' + options.ip + ':8082',
'webpack/hot/only-dev-server',
"./app/src/pages/dashboard/main.js"]
},
output: {
path: options.production ? './dist' : './build',
publicPath: options.production ? '' : 'http://' + options.ip + ':8081/',
filename: options.production ? '[name].app.[hash].min.js' : '[name].app.js',
},
plugins: options.production ? [
//new DashboardPlugin(),
// Important to keep React file size down
new CommonsChunkPlugin("commons.chunk.js"),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production'),
},
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
minimize: true,
beautify: false,
comments: false,
compress: {
warnings: false,
},
mangle: {
// Don't mangle $
except: ['$', '_', '*', '$super', 'exports', 'require'],
// Don't care about IE8
screw_ie8: true,
// Don't mangle function names
keep_fnames: true
}
}),
//new ExtractTextPlugin('app.[hash].css'),
new HtmlWebpackPlugin({
template: './conf/tmpl.html',
production: true,
filename: "index.html",
excludeChunks: ['admin']
}),
new HtmlWebpackPlugin({
template: './conf/tmpl.html',
production: true,
filename: "admin.html",
excludeChunks: ['interview']
}),
new webpack.DefinePlugin({ //export all environment variables
//todo check that if this is really working
'process.env': {
DENEME: JSON.stringify("mesut"),
APPCONFIG: JSON.stringify(confParams)
}
})
] : [
new CommonsChunkPlugin("commons.chunk.js"),
new HtmlWebpackPlugin({
template: './conf/tmpl.html',
filename: "index.html",
excludeChunks: ['admin']
}),
new HtmlWebpackPlugin({
template: './conf/tmpl.html',
filename: "admin.html",
excludeChunks: ['interview']
}),
new webpack.DefinePlugin({ //export all environment variables
//todo check that if this is really working
'process.env': {
DENEME: JSON.stringify("mesut"),
APPCONFIG: JSON.stringify(confParams)
}
})
],

Webpack: You may need an appropriate loader to handle this file type

I have a little nodejs project with webpack. Iam relatively new to webpack so i think thats the problem.
If i install log4js, winston or other logger libraries and run the application i am getting
WARNING in ./~/log4js/lib/log4js.js
Critical dependencies:
388:21-38 the request of a dependency is an expression
# ./~/log4js/lib/log4js.js 388:21-38
WARNING in ./~/log4js/lib/appenders/logstashUDP.js.orig
Module parse failed: /Users/me/Development/jstemplate/node_modules/log4js/lib/appenders/logstashUDP.js.orig Line 31: Unexpected token <<
You may need an appropriate loader to handle this file type.
|
| var logObject = {
| <<<<<<< HEAD
| '#timestamp': (new Date(loggingEvent.startTime)).toISOString(),
| type: type,
# ./~/log4js/lib/appenders ^\.\/.*$
here is my webpack config
var webpack = require('webpack');
var path = require('path');
var APP_DIR = path.join(__dirname, '..', 'src');
var devFlagPlugin = new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(process.env.DEBUG || 'false'))
});
module.exports = {
debug: true,
devtool: 'eval',
entry: ['webpack-hot-middleware/client', './src/index.tsx'],
module: {
preLoaders: [{
test: /\.tsx?$/,
loader: 'tslint',
include: APP_DIR
}],
loaders: [{
test: /\.tsx?$/,
loaders: ['babel', 'ts'],
include: APP_DIR
}]
},
output: {
filename: 'app.js',
path: path.join(__dirname, '..', 'build'),
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
devFlagPlugin
],
resolve: {
root: [path.resolve('../src')],
extensions: ['', '.jsx', '.js', '.tsx', '.ts', '.json']
},
resolveLoader: {
root: '../node_modules'
},
node: {
fs: "empty"
}
};
Open this file. It is corrupted.
var logObject = {
<<<<<<< HEAD
'#timestamp': (new Date(loggingEvent.startTime)).toISOString(),
type: type,
message: logMessage,
fields: fields,
category: loggingEvent.logger.category
=======
"#version" : "1",
"#timestamp" : (new Date(loggingEvent.startTime)).toISOString(),
"type" : config.logType ? config.logType : config.category,
"message" : layout(loggingEvent),
"fields" : _.extend(config.fields,
loggingEvent.data.length > 1 ? loggingEvent.data[1] : {},
{'level':loggingEvent.level.levelStr})
>>>>>>> jumpgh-master
};
Looks like merge conflict. Looks like problem with this module, not with webpack.

Categories

Resources