Webpack类优先级

时间:2016-08-11 00:50:58

标签: javascript webpack babeljs

我使用webpack(使用ES5到ES6 transile)并尝试构建bundle.js。 但是我在Chrome中收到一条错误消息: index.js:3未捕获的ReferenceError:网格未定义

我的入口点(index.js):

require('./Grid');
new Grid();

我的(Grid.js)

export class Grid
{
    constructor()
    {
        alert('Hello World');
    }
}

Webpack配置

var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');

module.exports = {
    context: path.join(__dirname, "src/js"),
    devtool: debug ? "inline-sourcemap" : null,
    entry: __dirname + '/src/js/index.js',
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /(node_modules|bower_components)/,
                loader: 'babel-loader',
                query: {
                   presets: ['es2015']
               }
            }
       ]
   },
   output: {
       path: __dirname + "/dist/js/",
       filename: "bundle.js"
   }
};

有什么问题?

2 个答案:

答案 0 :(得分:2)

当您使用Babel的export时,您必须小心使用require。这就是CommonJS在几种不同情况下的工作方式:

// Classic CommonJS default export
module.exports = Grid;
// Import with one of:
import Grid from './Grid.js';
const Grid = require('./Grid.js');

// Babel ES6 default export
export default class Grid {}
// Import with one of:
import Grid from './Grid.js';
const Grid = require('./Grid.js').default; // Babel exports it as named property default
// The export is more or less equivalent to (but you shouldn't write this yourself)
module.exports = { default: Grid, __esModule: true }; // (__esModule is a Babel internal)

// Named CommonJS/ES6 export:
module.exports = { Grid: Grid };
// Equivalent to
export class Grid {} // no default = export named
// or 
export { Grid }; // with Grid created earlier
// Import with one of:
import { Grid } from './Grid.js';
const Grid = require('./Grid.js').Grid;

如果我没有弄错的话,随着Babel 6的引入而改变了。 Babel 5导出默认属性的方式与经典CommonJS默认导出的方式相同。为了更好地实现ES6规范,它已被更改。

答案 1 :(得分:1)

以下两项更改似乎解决了我的问题:

  1. Grid.js:将export class Grid...更改为module.exports = class Grid...

  2. index.js:将require('./Grid');更改为 var Grid = require('./Grid'); import Grid from './Grid';