0

I have a file that I want available app wide, if the file is called app_wide.js normally I would do

import util from './app_wide.js'

However, I it is a small file and I want its exports available in all my files without the explicit import command. How can I go about doing this?

I'm using Webpack to build a React application.

  • Does this answer your question? [Make global function in webpack](https://stackoverflow.com/questions/41797042/make-global-function-in-webpack) – code Dec 28 '21 at 23:02
  • I imagine that would work, but it is messy ... I would have to do `window.holder.func1()`, instead of `holder.func1()`. I'm not sure if is good practice to use globals in this way as well. – user17331023 Dec 28 '21 at 23:06
  • How about this one: https://stackoverflow.com/questions/37656592/define-global-variable-with-webpack – code Dec 28 '21 at 23:07
  • Why don't you want the explicit import? – Andy Dec 28 '21 at 23:08
  • There is no other way besides polluting the global namespace or getting webpack to replace the code strings. Usually, however, even a util function that is used in every single other module will be imported every time. I use typescript paths so I can write `import { common } from "@utils"`. – windowsill Dec 28 '21 at 23:16
  • @Andy - it's messy, if I want to use a simple custom log function, I have to update all the files with two lines of code instead of one. I've even seen some React apps that no longer require the import React ... statement ... that is probably a different method all together ... I'm not sure how they do it but code reduction helps maintenance. I think webpack has a way to do this as well. – user17331023 Dec 29 '21 at 00:35

1 Answers1

0

Maybe you can use webpack provide-plugin https://webpack.js.org/plugins/provide-plugin/

for example:

hello.js

const hello = () => {
  console.log('hello');
};

module.exports = hello;

webpack.config.js

plugins: [
      new webpack.ProvidePlugin({
        $hello: path.resolve(path.join(__dirname, './hello.js'))
        // ...
      })
]

App.js

// don't need imported or required hello from 'hello.js'
$hello()

when you use typescript don't forget to declare the type

hello.d.ts

declare function $hello(): void;
yuchang
  • 86
  • 2