javascriptimport

How can i import a lib in global so i can access it in an imported js file?


Why i think that put my lib in global and access it in different files is a valid choice : First i have one js file, but my file was getting bigger so i just separate it in two, and now i access to my second file functions with an export of functions. So why do i have to import one time the lib when im on a single file, but multiple times when i use multiple files

What i want to do

I have an error when i try to use a lib in JavaScript.

For the example i will use 'lib' instead of a real library from js

This is my files

app.js

import lib from 'lib'

console.log(lib)

This is working, but when i add

app.js

import lib from 'lib'
import my_file from './file_path.js'

file_path.js

console.log(lib)

This is not working and i have to import my lib in the new file like

file_path.js

import lib from 'lib'
console.log(lib)

I GET THIS ERROR

Uncaught ReferenceError: lib is not defined

But i don't want to duplicate my import, How can i do it ? thanks


Solution

  • /!\ You have to be in a node application to use this method /!\

    I also find an alternative of the window and import

    We can use require like that:

    window.lib = require('lib');
    

    Now we just have one line instead of 2 This is the best solution i found so far, don't know if we can do better, let me know