CRA webpack - output separate files - reactjs

I've got a CRA app that I have built as a Chrome Extension, however I need to implement https://github.com/tshaddix/react-chrome-redux
To do so, I need to build my background.js as its own file, as well as the main.js
I've added my path to config/paths.js
backgroundJs: resolveApp('src/background.js'),
and my config contains:
entry: [require.resolve('./polyfills'), paths.appIndexJs],
output: {
path: paths.appBuild,
filename: 'static/js/[name].js',
publicPath: publicPath,
Does anyone know how I can keep my src file built into main.js, but have background.js build to its own file?

You can pass an object to entry:
module.exports = {
/* ... */
entry: {
main: [require.resolve('./polyfills'), paths.appIndexJs],
background: resolveApp('src/background.js'),
}
/* ... */
}
Check the document: https://webpack.js.org/concepts/entry-points/.

Related

monaco-editor-webpack-plugin Create React App Build with react-router causing incorrect location for chunks

Getting the below error, it should be: http://localhost:4000/webapp/static/js/328.f5f431ed.chunk.js
This only happens for production builds and not development running.
It is appending to the end of the react router route. Not sure how to configure this properly?
Uncaught (in promise) ChunkLoadError: Loading chunk 328 failed.
(missing: http://localhost:4000/webapp/editor/ae2c222b-fc4b-40b7-bfae-7a0750c011fc/static/js/328.f5f431ed.chunk.js)
at Object.__webpack_require__.f.j (jsonp chunk loading:27:18)
Tried to change the config - tried different combinations of this and can't get it to work.
craco.config.js
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
module.exports = {
webpack: {
output: {
publicPath: '/webapp/',
},
plugins: [new MonacoWebpackPlugin({ publicPath: '/webapp/', languages: ['json', 'python', 'shell', 'python']})],
},
};
Managed to figure this out
In package.json instead of
"homepage": ".",
use:
"homepage": "/webapp/",

Ejected React app stuck on “Starting the development server” after changing entry config

I need to support multiple entry points in the React App. One of the option to do that is via eject: npm run eject.
Here is an original source I use How to Add Multiple Entry Points to Your React App
Create a new application and eject it:
$ npx create-react-app react-hello
$ cd react-hello
$ npm run eject
Then add into App.js:
import React from "react";
And start application to make sure it works with default configuration:
$ npm start
To be able to have multiple entry points, I have to adopt the configuration of entry in the config/webpack.config.js. Original configuration looks like (without comments):
entry: [
isEnvDevelopment &&
require.resolve('react-dev-utils/webpackHotDevClient'),
paths.appIndexJs,
].filter(Boolean),
To support multiple entries, I have to convert it into the associative array/hash table, in this case I use index as a key for the default index page:
entry: {
index: [
isEnvDevelopment && require.resolve('react-dev-utils/webpackHotDevClient'),
paths.appIndexJs
].filter(Boolean)
},
And as soon as I change the format, the npm start stucks and Starting the development server... lasts forever. I try to build it and get an error:
$ npm run build
...
> node scripts/build.js
Creating an optimized production build...
Failed to compile.
Cannot read property 'filter' of undefined
Note: I haven't added a new entry yet, I only modify the current entry to be able to add another one later.
Webpack Entry Points says my configuration is correct.
What am I doing wrong and miss, could you please help?
I ran into this same issue. For me, the problem came from the "ManifestPlugin" further down. It looks like the initial configuration refers to the default "main" entry point key.
new ManifestPlugin({
fileName: 'asset-manifest.json',
publicPath: paths.publicUrlOrPath,
generate: (seed, files, entrypoints) => {
const manifestFiles = files.reduce((manifest, file) => {
manifest[file.name] = file.path;
return manifest;
}, seed);
// This next line is the problem!!!!
const entrypointFiles = entrypoints.main.filter(
fileName => !fileName.endsWith('.map')
);
return {
files: manifestFiles,
entrypoints: entrypointFiles,
};
},
}),
Because you made the entry point into "index" instead of "main", entrypoints.main is now undefined. If you were to change the above code to entrypoints.index, then the code should work as expected. However, this solution is not very flexible and only includes one entry point. The final solution I came up with was this.
new ManifestPlugin({
fileName: 'asset-manifest.json',
publicPath: paths.publicUrlOrPath,
generate: (seed, files, entrypoints) => {
const manifestFiles = files.reduce((manifest, file) => {
manifest[file.name] = file.path;
return manifest;
}, seed);
const entrypointFiles = Object.values(entrypoints).map(values => {
return values.filter(
fileName => !fileName.endsWith('.map')
)
});
return {
files: manifestFiles,
entrypoints: entrypointFiles,
};
},
}),
Encountered this issue using an ejected create-react-app 5.0.1 as-well.
In addition to the above answer, had to change the webpack output filename from static/js/bundle.js static/js/[name].js
output: {
filename: isEnvProduction
? "static/js/[name].[contenthash:8].js"
: isEnvDevelopment && "static/js/bundle.js
to
output: {
filename: isEnvProduction
? "static/js/[name].[contenthash:8].js"
: isEnvDevelopment && "static/js/[name].js"

Importing cdn of a local react webpack library giving a number in window object

I have two react projects where these two projects share some common components. I want to bundle those components as a library from project 1 with webpack and I don't want to publish them in any third party library tools, I want to use the project 1 cdn to get those components in project 2.
I followed this stackoverflow answer library of react components in webpack bundle export to use in on runtime rendering
but I'm getting Extract.entity value in window object as 1 (a number) instead of function or a class. This is my webpack config.
entry: {
app: paths.appIndexJs
},
output: {
path: paths.appBuild,
filename: "static/js/[name].js",
publicPath: publicPath,
library: ["Extract", "entity"],
libraryTarget: "umd",
umdNamedDefine: true,
globalObject: "this",
devtoolModuleFilenameTemplate: info =>
path.relative(paths.appSrc, info.absoluteResourcePath).replace(/\\/g, "/")
}
The following is the output of window object in console
Extract:{
entity: 1
}

React multiple output files of bundle of single Input file

I am working in React and want to publish my code . I am creating bundle using webpack , since I want the bundle to be divided in three parts , that is , my code should have divided in to three different files so that not only one file get populated too much . I went through the official docs of webpack and other online sites but still not found the solution for this .
Here is a complete configuration webpack.config.js that you can base yours on.
const webpack = require('webpack');
const CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;
const WebpackConfig = {
// multiple component entry points
entry: {
AppPart1: './src/AppPart1',
AppPart2: './src/AppPart2',
AppPart3: './src/AppPart3'
},
// generate files
output: {
path: './assets',
// creates JS files like "AppPart1.js"
filename: '[name].js'
},
module: {
preLoaders: [
// add any pre-loaders here, OPTIONAL
],
loaders: [
// add any loaders here, like for ES6+ transpiling, React JSX etc
]
},
resolve: {
extensions: ['.jsx', '.js']
},
plugins: [
// this will factor out some common code into `bundle.js`
new CommonsChunkPlugin('bundle.js'),
]
};
module.exports = WebpackConfig;
At the end of webpack build, here is what you will have in the assets folder
AppPart1.js
AppPart2.js
AppPart3.js
bundle.js
bundle.js will contain some shared code and must be included on all your pages along with the appropriate part file for the page.
If you have the three separate files, you can put multiple entry points on your webpack config:
entry: {
"bundle1":"./src/app/somefile1.jsx",
"bundle2":"./src/app/somefile2.jsx,
"bundle3":"./src/app/somefile2.jsx"
}

Webpack output chunk as commonjs2 library

I'm trying to make some React Isomorphic/Universal magic and I needed to be able to require in Node an exported chunk.
I'd like to do something like this:
webpack.config.js
module.exports = {
entry: {
index: [
'./src/index',
],
},
output: {
path: path.join(__dirname, '/dist'),
filename: '[name].js',
chunkFilename: 'chunk-[name].js',
libraryTarget: 'commonjs2',
},
...
};
index.jsx
require.ensure(['./reducers', './routes'], (require) => {
const rootReducer = require('./reducers');
const routes = require('./routes');
/* Store/routes/configuration stuff */
ReactDOM.render(/* components */);
}, 'core');
So this would output two files:
index.js: Loaded by the browser
chunk-core.js: required by index AND Node server
If I set the output as a library with type commonjs2 it works on Node, but does not generate my browser bundle, so I'd have to run 2 webpack configs simultaneously: one for the browser bundle and another for the server library.
I'd like to know if any of these are possible:
output a chunk as commonjs2 library
output a chunk with a different target as the main output
import a standard webpack chunk in Node

Resources