【问题标题】:Webpack class priorityWebpack 类优先级
【发布时间】:2016-12-17 13:30:01
【问题描述】:

我使用 webpack(带有 ES5 到 ES6 的转译)并尝试构建 bundle.js。 但我在 Chrome 中收到一条错误消息:index.js:3 Uncaught ReferenceError: Grid is not defined

我的入口点(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"
   }
};

怎么了?

【问题讨论】:

    标签: javascript webpack babeljs


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案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 规范,它进行了更改。

      【讨论】:

        猜你喜欢
        • 2020-02-06
        • 2010-11-10
        • 2011-06-25
        • 1970-01-01
        • 1970-01-01
        • 2011-12-20
        • 2014-12-01
        • 2023-03-12
        • 2015-02-17
        相关资源
        最近更新 更多