I'm using "vite": "^2.8.6" for React project. What I know is that Vite is using Rollup as module bundler, but I stumbled on a problem where Rollup still bundling my react-dom.development.js and react.development.js. I've used "rollup-plugin-replace" to replace my 'process.env.NODE_ENV' to production, but the problem still occur. Here is the my rollup config:
rollupOptions: {
// https://reactjs.org/docs/optimizing-performance.html#rollup
plugins: [
rollupPluginReplace({
'process.env.NODE_ENV': JSON.stringify('production')
}),
rollupPluginCommonjs(),
terser(),
visualizer()
],
},
When I analyze with rollup-visualizer, you can see that rollup bundled both production and development dependency, which supposedly only bundled one of them right?
The problem with this is that there is extra 1MB of dead code in the bundle, it will be great if I can eliminate it.
This generally means that rollup does not understand that your app is directed towards production code. In my case it was because I had set up library mode.
lib: {
entry: './src/app.ts',
fileName: 'app.ts',
name: 'AppClass',
formats: ['iife'],
}
Removing this block finally generated a build which was sane in size. For more information, see the vite documentation.
If you were also trying to get vite/rollup to build your app as an IIFE, setting rollupOptions worked for me:
rollupOptions: {
output: {
entryFileNames: `[name].js`,
assetFileNames: `app.[ext]`,
format: 'iife',
},
input: ['./src/app.ts'],
},
Related
I have a mature CRA-based React app running with Webpack 5. I would like to have a separate project (in git, etc) where Storybook lives and points to the components in the app. (The app has tons of devs in and out of it, and dropping a bunch of Storybook packages in there, as well as introducing legacy-peer-dependencies thanks to webpack 5, would be quite frowned upon).
I also want devs to have a good experience being able to use Storybook to write components, so I want Storybook to see the current code of the project components, not some exported package. And same as above, there are many devs and a lot of inertia, so moving components to a separate standalone library is not an option.
My ideal for local development:
components and stories: /MyProject-App/src/Components/...
storybook app. : /MyProject-Storybook/stories/...
(Production I'm not worried about yet)
Installing Storybook inside the app works fine (as long as you run with --legacy-peer-deps). I am using the npx storybook init script and it works fine. But if I try to run Storybook out of a separate directory and target the app directory's Components, it breaks. If I run Storybook out of the app, and point it to stories/components outside that repo (which I copied and pasted just as a debugging measure), it breaks. Going up and out of the current project root breaks.
To do this, I am trying to point stories in /MyProject-Storybook/.storybook/main.js to ../../MyProject-App/src/Components.... When I do this and npm run storybook, I get the error output:
File was processed with these loaders:
* ./node_modules/#pmmmwh/react-refresh-webpack-plugin/loader/index.js
* ./node_modules/#storybook/source-loader/dist/cjs/index.js
**You may need an additional loader to handle the result of these loaders.**
The error is always on some basic ES6 syntax, arrow functions etc. If I run the same Storybook install out of MyProject-App (same version numbers / same main.js just pointed at the local path instead of the ../other path) it works.
In addition to this, I tried it the other way - running storybook out of the App folder (where I know it runs), and only changing the main.js stories directory to an outside-that-repo folder where I copied my Components and stories into. It breaks in the same way - I get the same You may need an additional loader to handle the result of these loaders. message, with it pointing to any example of ES6 syntax as an 'error'.
I found this similar question - Storybook can't process TS files outside of the project
recommending to look into Storybook's webpack loaders - https://storybook.js.org/docs/react/builders/webpack
So I updated my .storybook/main.js to be the following:
module.exports = {
stories: [
'../../MyProject-Storybook/src/**/*.stories.mdx',
'../../MyProject-Storybook/src/**/*.stories.#(js|jsx|ts|tsx)'
],
addons: [
'#storybook/addon-links',
'#storybook/addon-essentials',
'#storybook/addon-interactions',
'#storybook/preset-create-react-app'
],
framework: '#storybook/react',
core: {
builder: '#storybook/builder-webpack5'
},
webpackFinal: async (config, { configType }) => {
config.module.rules.push({
test: /\.(js|jsx)$/,
use: [
{
loader: require.resolve('babel-loader'),
options: {
reportFiles: ['../**/src/**/*.{js,jsx}', '../../MyProject-Storybook/**.stories.{js,jsx}']
}
}
]
});
config.resolve.extensions.push('.js', 'jsx');
return config;
}
};
but to no avail - output from npm run storybook remains unchanged, an excerpt:
File was processed with these loaders:
* ./node_modules/#pmmmwh/react-refresh-webpack-plugin/loader/index.js
* ./node_modules/#storybook/source-loader/dist/cjs/index.js
You may need an additional loader to handle the result of these loaders.
| backgroundColor: { control: 'color' },
| },
> } as ComponentMeta<typeof Button>;
|
I was able to bundle my React Component library in Rollup, but I wanted the features of Vite for development and installed in over the weekend. My problem is that now I'm getting the following error when I try to npm link my vite generated distribution with another react probject.
Basically it's saying that it can't use useContext when it gets the 'Provider" which is really just a react context. It seems like it's having a problem here in the bundle when it tries to load it:
var Context=/*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createContext(null);
My vite config looks as such:
export default defineConfig({
plugins: [react(), dts({ insertTypesEntry: true })],
build: {
lib: {
entry: path.resolve(__dirname, "src/lib/index.ts"),
name: "MyLib",
formats: ["umd", "es"],
fileName: (format) => `my-lib.${format}.js`,
},
rollupOptions: {
external: [ "react", "react-dom" ]
}
},
});
Searching said that it might be a problem with my dependencies, using two versions of react or react-dom. I've tried it with every dependency configuration I can think of and it all breaks in different ways. I think maybe npm cacheing could be confusing me or something though.
Have any ideas? Vite works fine in 'dev' mode, and the components were working ok in Rollup so I feel like it's just a dumb configuration thing I don't understand
I am getting a syntax error in IE when this component of react is loaded in the webpage. Has anybody got the same problem? This is an inherited package, and a syntax error from node_modules makes no sense?
"use strict";
/* WEBPACK VAR INJECTION */(function(module) {
const colorConvert = __webpack_require__(/*! color-convert */ "./node_modules/color-convert/index.js");
const wrapAnsi16 = (fn, offset) => function () {
const code = fn.apply(colorConvert, arguments);
return `\u001B[${code + offset}m`;
};
const wrapAnsi256 = (fn, offset) => function () {
const code = fn.apply(colorConvert, arguments);
return `\u001B[${38 + offset};5;${code}m`;
};
If you are using newer versions of Node/NPM, check your package.json file -> "browserslist" section.
This is the default "browserslist" created for you if you do not have one defined:
In this case, if you run "npm start" on your LOCAL Environment, Babel will not create Polyfills for IE11 because its not included as a target browser in "development". To get this working, I deleted my node_modules directory completely, ran 'npm install', updated package.json with:
and ran 'npm start.
The reason why this fails is that babel or your other favorite transpiler might ignore node_modules (if that's how its configured), so you need to include it manually because IE does not support arrow function syntax.
First, if you search for wrapAnsi16 or wrapAnsi256 function names online it'll point you to common npm packages, such as: ansi-styles, chalk or color-convert, debug, strip-ansi, etc.
If you are using Webpack you can add the following to your rules:
module: {
rules: [{
exclude: /node_modules\/(?!(color-convert|ansi-styles|strip-ansi|ansi-regex|debug|react-dev-utils|chalk)\/).*/
}]
}
or, easier to read:
module: {
rules: [{
include: [
path.resolve(__dirname, 'node_modules/ansi-styles'),
path.resolve(__dirname, 'node_modules/strip-ansi'),
... other's here...
path.resolve(__dirname, 'src'),
]
}]
}
Hope this helps somebody in the future ;)
TLDR; you don't need this library, just run
npm run build
And it will be excluded from your build.
I have same problem with create-react-app, and I solve it (no). From my discovery, this library should not appear in browser, because it was designed for nodejs environment. Also I found, this library come to me as dependency of jest, and jest is dependency for tests and it come as dependency for react.
So, I run
npm run build
server -s build
And try my application in IE. And it work. So, when you run
npm start
It make file including dev dependencies and other garbage that should not appear in production and in browser at all. When you run
npm run build
It make file only with required project libraries.
I had similar issue #punkbit solution and installing 'react-app-polyfill'
and importing it at the top of the index.js file solved it
import 'react-app-polyfill/ie11';
import 'react-app-polyfill/stable';
If it still does not work delete node-modules and reinstall also clear cache in IE.
All the best :)
This problem occurs because your compiled code contains (modern) ES6 syntax whilst IE11 only supports ES5.
A way to fix this is to instruct webpack to specifically compile the mentioned packages into ES5;
module: {
rules: [{
test: /\.(tsx?|js)$/,
include: [
// These dependencies have es6 syntax which ie11 doesn't like.
// Whenever you see a "SyntaxError" that crashes IE11 because of a new lib, add it here.
path.join(__dirname, 'node_modules/react-intl'),
path.join(__dirname, 'node_modules/pkce-challenge'),
path.join(__dirname, 'node_modules/fuse.js')
],
use: [{
loader: 'ts-loader', // Or whatever loader you're using
}]
}]
}
for me this was: fuse.js, pkce-challenge and react-intl.
I am attempting to do some code-splitting in my create-react-app application that utilizes server side rendering.
I am utilizing 'react-loadable` to do the code-splitting: https://github.com/thejameskyle/react-loadable
As of now I simply have split my Home.js component away from the rest of my app, just to see if it works. In development mode (read: not SSR), it's chunked off and works fine.
However, I can't get things to work on the server. I'm following the guide on their Github page and am stuck because of the webpack changes needed. In create-react-app applications, you don't have access to webpack as it's hidden away.
The error I receive when starting the server is:
return (0, _importInspector.report)(import('../components/home/Home'), {
^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:80:10) ...
I'm pretty sure it's because I don't have webpack configured correctly as stated in the guide.
In the guide, it clearly states for SSR:
First we need Webpack to tell us which bundles each module lives inside. For this there is the React Loadable Webpack plugin.
Import the ReactLoadablePlugin from react-loadable/webpack and include it in your webpack config. Pass it a filename for where to store the JSON data about our bundles.
// webpack.config.js
import { ReactLoadablePlugin } from 'react-loadable/webpack';
export default {
plugins: [
new ReactLoadablePlugin({
filename: './dist/react-loadable.json',
}),
],
};
I don't think this is possible without ejecting.
Anyone have any idea if react-loadable can be used in a create-react-app server-side-rendered application?
import these modules at the top of your server file
require('ignore-styles');
require('babel-polyfill')
require('babel-register')({
ignore: [ /(node_modules)/ ],
presets: ['es2015', 'react-app'],
plugins: [
'syntax-dynamic-import',
'dynamic-import-node',
'react-loadable/babel'
]
});
I'm using webpack as my bundler and I'd like to test the real performance sometimes without having to actually bundle the whole application. Is there a way how to temporarily turn off React development mode? As far as I know, the production version of React is actually a different file with all the extra debug info stripped but I don't know how to enforce which version should be loaded.
Tell Webpack to use Node's production environment. One way of doing this is to use DefinePlugin in your Webpack config to set the process.env to production:
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify("production")
}
})
]
Also make sure to use a production-ready devtool option, e.g. devtool: 'cheap-module-source-map' and not devtool: 'eval' (also in your Webpack config).
The production version of React is just the .min.js version. From the download page:
We provide two versions of React: an uncompressed version for development and a minified version for production. The development version includes extra warnings about common mistakes, whereas the production version includes extra performance optimizations and strips all error messages.
So if you include this in your asset pipeline, instead of the uncompressed version, you will be able to test your app in 'production' mode.
Assuming you install React 15.0.1 with npm, import react from 'react' or react = require('react') will run ./mode_modules/react/lib/React.js which is React's raw source.
The React docs suggest you use ./mode_modules/react/dist/react.js for development and react.min.js for production.
Should you minify /lib/React.js or /dist/react.js for production, React will display a warning message that you've minified non-production code:
Warning: It looks like you're using a minified copy of the development build of React. When deploying React apps to production, make sure to use the production build which skips development warnings and is faster. See fb.me/react-minification for more details.
react-dom, redux, react-redux behave similarly. Redux displays a warning message. I believe react-dom does too.
So you are clearly encouraged to use the production version from /dist.
However if you minify the /dist versions, webpack's UglifyJsPlugin will complain.
WARNING in ../~/react/dist/react.js
Critical dependencies:
4:478-485 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results.
# ../~/react/dist/react.js 4:478-4851
You cannot avoid this message because UglifyJsPlugin can only exclude webpack chunks, not individual files.
I use the both the development and production /dist versions myself.
Webpack has less work to do and finishes a bit sooner. (YRMV)
React docs say /dist/react.min.js is optimised for production. I've read no proof, just handwaving, that 'process.env': { NODE_ENV: JSON.stringify(IS_PRODUCTION ? 'production' : 'development') } plus uglify does as good a job as '/dist/react.min.js`.
I get 1 warning message from uglify rather than 3 from the react/redux ecosystem.
You can have webpack use the /dist versions with:
resolve: {
alias: {
'react$': path.join(__dirname, 'node_modules', 'react','dist',
(IS_PRODUCTION ? 'react.min.js' : 'react.js')),
'react-dom$': path.join(__dirname, 'node_modules', 'react-dom','dist',
(IS_PRODUCTION ? 'react-dom.min.js' : 'react-dom.js')),
'redux$': path.join(__dirname, 'node_modules', 'redux','dist',
(IS_PRODUCTION ? 'redux.min.js' : 'redux.js')),
'react-redux$': path.join(__dirname, 'node_modules', 'react-redux','dist',
(IS_PRODUCTION ? 'react-redux.min.js' : 'react-redux.js'))
}
}