Webpack es2015:浏览器无法找到类

时间:2018-03-10 06:18:52

标签: webpack ecmascript-6

我有代码test.js

import * as engine from "./ctest"

var t = new engine()
t.init()

src/ctest.js是:

class engine {

    constructor() {
        console.log('test constructor test');
    }

    init() {
        console.log('popl');
    }
}

module.exports = engine; 

我的webpack.config.js是:

'use strict';

var path = require('path');
var root = path.resolve(__dirname);

module.exports = {
    entry: ["./src/test.js"],

    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: "test.js"
    },

    module: {
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /(node_modules)/,
            }
        ]
    }
};

我的.babelrc

{
    "presets": ["env"]
}

当我使用npm run watch编译它并在浏览器中启动它时出现控制台错误:

Uncaught ReferenceError: engine is not defined
at eval (test.js:9)
at Object../src/test.js (test.js:94)
at __webpack_require__ (test.js:20)
at eval (test.js:1)
at Object.0 (test.js:105)
at __webpack_require__ (test.js:20)
at test.js:69
at test.js:72" 

engine = new engine();

1 个答案:

答案 0 :(得分:0)

安装babel-preset-env&删除所有其他预设。另请注意,您不需要在presets.babelrc中提及query数组。 js测试中的.babelrc字段。仅在query&删除npm install --save-dev babel-preset-env字段。

首先npm remove babel-preset-es2015 babel-preset-stage-2& import engine from "./src/ctest"; const t = new engine(); t.init();

完整的结构如下所示。

test.js

class engine {
  constructor() {
    console.log("test constructor test");
  }

  init() {
    console.log("popl");
  }
}

module.exports = engine;

的src / ctest.js

{
  "presets": ["env"]
}

.bablerc

const path = require("path");

module.exports = {
  entry: "./test.js",

  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "engine.js"
  },

  module: {
    rules: [
      {
        test: /\.js$/,
        loader: "babel-loader",
        exclude: /(node_modules)/
      }
    ]
  }
};

webpack.config.js

{
  "name": "Webpack-testing",
  "version": "1.0.0",
  "description": "",
  "main": "webpack.config.js",
  "scripts": {
    "build": "webpack --mode development",
    "prod": "webpack --mode production",
    "start": "node dist/engine.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.4",
    "babel-preset-env": "^1.6.1",
    "webpack": "^4.0.0-beta.3",
    "webpack-cli": "^2.0.11"
  }
}

的package.json

sheetname0['A1']

现在第一个错误是 webpack.config.js 中的输入点错误。 Webpack需要包含所有其他文件的主文件。所以在你的情况下它的 test.js 包括 src / ctest.js &不是相反,所以它应该是切入点。

要运行该应用程序,请尝试 npm run build npm run prod &然后运行 npm run start 。请注意,我正在使用Webpack 4,这就是构建&中标志 - 模式的原因。 package.json

中的 prod 脚本