I would like to know the best practices for importing es6 modules to global.

Asked 2 years ago, Updated 2 years ago, 44 views

I implement js using babelify.
Among them, when using libraries such as react, underscore, and jquery, I think it is often used throughout the application.
How should I deal with this global use?

When implementing with React, I import each file I use as follows:

import Reacr from 'react';

This is not a problem, but I would appreciate it if you could share any improvements or better ways.
Thank you for your cooperation.

javascript reactjs

2022-09-30 10:47

1 Answers

Let me write down some approaches.

For React, the node_modules/react/dist directory contains compiled files for the browser.
Copy this (or symbolic link) and

<script src="lib/react.min.js"></script>

The global variable React is then available throughout the script.
This is the closest method to traditional methods.
If you have React on multiple pages, you can also benefit from efficient caching.

import at the first place to run only once (for example, the first file to pass to Browserify) and place it in the global area.

import React from "react";
Function("return this;")().React=React;

If you are using Modules, Global thisis not available as an alias for the host object.
That's how it looks like this.I'm sure it will work...

Personally, I think this is the best.


2022-09-30 10:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.