简体   繁体   中英

How can I include a global JS file to my React project using webpack?

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?

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM