Anton Stafeyev
Anton Stafeyev

Reputation: 831

Webpack exported variable is not visible by browser

Here is my bundle file, i have included components here.

import Container from './Components/Container/Container.component.js';
import Heading from './Components/Heading/Heading.component.js';

const Components  = {

  Container: Container,
  Heading: Heading
}

module.exports = Components;

the goal is to make this Components variable visible in the browser tag. so far console.log(Components) is undefined.

module.exports = {
entry: {
    bundle: "./src/bundle.js"
},
output: {
    path: path.resolve(__dirname, "dist/js"),
    filename: "bundle.js",
    library: "Components",
    libraryTarget: "var",
},

module:{
    rules: [
        {
            test: /\.js$/,
            exclude: path.resolve(__dirname, "node_modules"),
            use: {
                loader: "babel-loader",
                options: {
                    presets: ["env", "react"]
                }
            }
        }
    ]
},

target: "web"
}

And this is my webpack config file. what do i do inside my webpack config to make Components to be visible in browser without assigning it to window object. in other words, make it global and beign able to import it via webpack into other js files.

Upvotes: 2

Views: 2010

Answers (1)

Anton Stafeyev
Anton Stafeyev

Reputation: 831

SOLUTION (as i understood it and here is a duplicate actually, answered by @dreyescat)

1) Output target must be a library. so webapck output should look like

output: {
    path: path.resolve(__dirname, "dist/js"),
    filename: "Bundle_name",
    library: "Library_name",
    libraryTarget: "var" //See below
},

libraryTarget: "var" - (default) When your library is loaded, the return value of your entry point will be assigned to a variable - https://webpack.js.org/configuration/output/#output-librarytarget

For those who are looking to do the same make sure you export your varibale as

module.exports = your_variable;

So for some reason i had it all in my file and it didn't work, and i used webpack --watch. i ran webpack without watch to compile it once and it worked. not sure why.

it just doesn't work with webpack-cli --watch, while webpack --watch is totaly fine

Upvotes: 1

Related Questions