1

I'm using React for he first time and I discover that there are some JS functions I need to use accross multiple JSX files.

I've looked at some examples, but can't figure out how to correctly include my global.js file.

My folder structure:

/dist
/src
  /components
  /sass
  /img
  index.js
  global.js
webpack.config.js

This is my webpack file:

var path = require('path');
var webpack = require('webpack');

module.exports = {
    entry: "./src/index.js",
    output: {
        path: __dirname + "/js/",
        filename: "bundle.js"
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                loader: 'babel',
                query: {
                    cacheDirectory: true,
                    presets: ['es2015', 'react']
                }
            }
        ]
    }
};

Can anyone tell me how to correctly include this one file and where in the webpack code this goes?

1 Answer 1

1

I am not sure about what you need, but webpack is your building system, so it plays at an lower level from what do you want. If you want to include functions in various file, you need to include the file in wherever you need it:

global.js

module.export = {
 func1: ..,
 func2: ..
}

file where you need a function:

var globals = require('path/to/global.js')
Sign up to request clarification or add additional context in comments.

3 Comments

I need the functions in global.js to be accessible from any *.jsx file.
the only way I know is to required it in every file (for example, when using react you need to require react in everyfile, so I don't see the problem of adding one more line). Maybe there is a way to add your code during the building phase to each file, but does not seems a good practice to me
@Steven I think you should be a loader: webpack.github.io/docs/how-to-write-a-loader.html This is what you need to accomplish your goal

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.