gpt4 book ai didi

javascript - Webpack 类优先级

转载 作者:行者123 更新时间:2023-11-30 11:53:08 25 4
gpt4 key购买 nike

我使用 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"
}
};

怎么了?

最佳答案

当你使用 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 规范,对其进行了更改。

关于javascript - Webpack 类优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38885685/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com