Does ReactJS reuse imported packages? - javascript

Does ReactJS reuse imported packages?
Let's say I have a file called DisplayItems.js and EditItem.js. They are both imported into App.js.
If I import a package (like axios) at the top of my DisplayItem.js file (import axios from 'axios';), and I also import it in my EditItem.js file, does my Application grow by 13kb or 26kb (assuming axios is 13kb)?

This behavior is controlled not by React, but by whatever build tool compiles and bundles your import statements into a JavaScript file for the browser.
The Create React App template currently uses Webpack as its build tool. Webpack avoids duplicating code that is imported multiple times; it only writes the definitions once. If you are using a different project setup for your React app, your project may use a different build tool.

In response to jhpratt, I did think of testing it on my own, but I knew it would take some time (about 34 mins).
Here's the test results.
Importing jQuery
2742120 (the control) - with jquery imported once
2742353 - with jquery imported twice (233 byte difference, .2kb)
2741887 - with jquery not being imported (233 byte difference, .2kb)
Importing modal-vanilla
2742120 (the control) - with modal-vanilla being imported once
2742406 - with modal-vanilla being import twice (286 byte difference, .3kb)
2712501 - with modal-vanilla not being imported (29386 byte difference, 29.3kb)
I'm not sure what was going on with jQuery (maybe I added it somewhere else in my project?), but it does look like packages are reused (at least in this instance).
Just in case anyone's wondering, I am using Laravel's React setup.

Related

Importing js modules by directory name

I'm upgrading a React application and have found that I need to modify the import statements to get them to work.
For example, in the old version, the following import works without errors:
import { User } from '../System'
Note that System is a directory on my file system that contains User, a js file that ends with export default User.
In my upgraded version of the app, the System directory still exists, but the above import gives me Can't resolve '../System' in 'C:\my app\.
It turns out that to get the import working properly now, I need to change it to the following:
import User from '../System/User';
If I understand correctly, this relates to js module system changes made with ES6.
My question, though, is regarding the specification of a directory in the import statement (System above). Why would it be that I was previously able to name a file directory in the import statement instead of the actual js script/module itself? Is that approach of using a directory in the import statement still possible? And if so, is it ever advisable?
Update: based on AKX's comment, I noticed the System directory does indeed contain an index.js, which apparently is what makes the import from the directory itself possible.
When an import points to a directory, and only a file, Webpack (which most React setups use) follows Node's's conventions and will attempt to import index.js from that directory if it exists. That's the only condition under which importing from a path that points to a directory works - your previous build probably had /System/index.js (which would allow importing with from '../System'). If you rename the file you're importing to anything else - such as to User.js - importing using only the directory path will fail.
And if so, is it ever advisable?
Sure, if you want. It's a style choice but is commonly done.

According to whether the package exists in the window or not load the package dynamically

Does any build tool support this loading strategy, such as webpack or rollup.js.
Build every dependency to a single bundle, and when loading these dependencies, firstly search it in window['package'], if exist, use it. Otherwise dynamic load dependencies bundle to use.
Such app dependency is React, ReactDOM and UiLib.
The built result is:
React -> a.js
ReactDOM -> b.js
UiLib -> c.js
my code -> d.js
if window.React exist but window.ReactDOM and window.UiLib does not exist. d.js should dynamically load b.js and c.js and use window.React.
I know I can config React to externals, but this is a microapp used in many different apps, I'm not sure which packages exist in every global.
Nope. It is not possible directly. For a bundler, it is a binary choice between bundle or not to bundle.
Why? When a bundler encounters a library via import statements like - import React from 'react', it needs to know what global object it should substitute whenever it encounters react package across the entire application dependency graph. This must happen at compile-time. Additionally, loading a library with dynamic decision at runtime means you are introducing an asynchronous behavior in your code which your components or application cannot handle readily.
There are two form factors - a library and application. As far as library is considered, this is the only way to teach bundler (either bundle it or leave it via externals).
At an application level, you can write your own code to partially achieve what you seek with help of CDN. For this, you use externals and tell Webpack, for example, that react will be available as global React object on window namespace.
Now before your library is getting consumed, you have to add a dynamic code where to check for presence of React object.
function async initialize() {
if (!window.React) {
const React = await import(/* webpackIgnore: true */ 'https://unpkg.com/react#18/umd/react.development.js')
window.React = React;
initializeMicroapp();
} else {
initializeMicroapp();
return Promise.resolve();
}
}
Your initialize function for microapp is async and returns a promise. This is usually the pattern to go ahead with shell + micro-frontends.
On a side note, you can use module federation approach which is actually meant to solve exactly similar use-case. With module federation, you can teach Webpack that if the host/shell provides a library, then Webpack should simply ignore its bundled copy of that library while serving only other necessary code. However, I advice caution as it is a very specific pattern and neither de-facto nor de-jure at this point. It is recommended when you are having sufficient scale and many independent teams working on same product space.

Does webpack code splitting work in react-native?

I am using in a web application react-router.
When using import 'lodash' I import the whole lodash lib in my project.
Code splitting is about using an async import using import().then() to dynamically load chunk while the application is running.
Read about code splitting in react-router/web.
For example: function atRuntime() { import('lodash').then(() => {});}
This will import the library at runtime with an ajax request so it is not bundled in the main.js.
I'd like to recycle my code between web and native and we use a lot of code splitting for each page change.
My app has two main parts and some user will only visit one part so they don't need all user authenticated part.
I expect to be able to use tree shaking during react-native, but it is missing in react-router/native documentation.
What's react-native opinion about code splitting?
if you want to use webpack, you can try with haul https://github.com/callstack/haul
but i highly recommend this implementation without webpack -> https://www.npmjs.com/package/react-native-bundle-splitter

How to import simple JS scripts "globally", using ES6 import or require?

I need to assimilate some code into a React app. Problem is, that the code i want to use comes from some example i found on the web, which uses "normal" tags to import various other scripts, via an HTML file.
The main script file that i want to use calls countless various functions from external scripts.(The script "assumes" those functions are available). This of course works in the browser, but not in a build system like Babel/Webpack.
To make things short: what would be the node/es6 equivalent of:
<script src="/dev/getHTMLMediaElement.js"></script>
And how do i make those functions available anywhere in the React app?
My React app is a fairly standard one, booted with react-create-app.
You can require or import this file directly after adding externals option in webpack config
Ref: https://webpack.js.org/configuration/externals/

Top level javascript imports - Redux

I'm trying to learn redux and I've run into an error. I only have two files, an index.html file and a main.js file, there are links to the jquery and redux cdns in the html file. I've only gotten to 2.3 in the redux tutorial(http://redux.js.org/docs/basics/Store.html) and am stuck. I have
import {createStore} from 'redux';
at the top of my main.js file, but when I load the application, I get an error pointing to line above saying
SyntaxError: import declarations may only appear at top level
What is a 'top level import declaration'?
Here is a gist to my code if that helps. https://gist.github.com/austincarvey/6e6c8fdc2640b0f9bbfb
The import directive is not recognised by web browsers. It's used at the compilation stage, to tie together different source files and third party modules into a single web bundle. If that doesn't make sense, then I highly recommended learning Babel and either Webpack or Browserify. Babel transpiles ES6 and React syntax to browser friendly ES5 code, whilst Webpack/Browserify bundle your modules.
For now however, if you just want to get on with learning Redux, you can simply remove the import statement and instead use the global variable Redux exposed by the redux CDN script in your gist. i.e.
var store = Redux.createStore(counterReducer);
import is used when you are including a file via es6 modules in a context that supports them (Browserify/Webpack/etc, future versions of browsers).
Since you are including the Redux lib via <script> tag, that takes care of including Redux in the global scope.
In the case of your gist, if you erase line one and change the createStore invocation to Redux.createStore on 29, everything should work.

Categories