简体   繁体   中英

Why can't I use a class from webpack bundled file?

I'm extremely new to using webpack. I'm trying to use it to bundle my framework. Anyways my framework's file looks something like this:

class Rorke {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
}

In my webpack.config.js:

module.exports = {
  entry: "./src/rorke.js",
  output: {
    filename: "rorke.bundle.js"
  }
}

My package.json:

{
  "name": "rorke-3.0",
  "version": "1.0.0",
  "description": "",
  "main": "./src/rorke.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "bundle": "webpack ./src/rorke.js dist/rorke.bundle.js"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^4.32.2"
  },
  "dependencies": {
    "pixi.js": "^5.0.3",
    "prototype": "0.0.5"
  }
}

So i run:

npm run bundle

And it outputs a bundle file. I then include that file like this:

<html>
  <body>
    <script src="dist/rorke.bundle.js"></script>
    <script src="game.js"></script>
  </body>
</html>

And finally, this is my game.js:

const game = new Rorke(800, 600);

So when i open the html file, it tells me:

Rorke is not defined

Does anyone know why this is the case? What am i doing wrong here/not understanding?

您需要的一切都在Webpack文档中: 创作库/暴露库

Developing a website really just means creating an HTML file, a CSS file, and a JavaScript file (or sometimes these are combined, or the CSS and JavaScript or combined, etc). These are just files served via a webserver on request.

I think one of the main reasons to use webpack is to follow require / import statements, that will convert client code spread across multiple files into a single bundle. Frontend development tooling, such as webpack allows for authoring these files as separate components.

Rorke is probably scoped to the bundle. So start with an index.js file, require / import your class, and then use that class. Then change your webpack root to be index.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