gpt4 book ai didi

javascript - 在 webpack 中包含 "es2015"加载器配置规则会导致要求在运行时返回未定义

转载 作者:行者123 更新时间:2023-12-03 06:05:10 24 4
gpt4 key购买 nike

我正在尝试使用 React 和 Webpack 为应用程序设置样板代码。我能够通过 webpack documentation 获得 webpack 设置。接下来,我尝试让 Babel 作为“加载器”来转译 JSX。上面的同一链接中有执行此操作的说明,但文档似乎不完整。除了上述说明之外,为了使 React 正常工作,我必须运行“npm install babel-preset-react”,然后将“react”和“es2015”添加到加载器配置中的查询参数中。然而,一旦我添加“es2015”,我就开始在浏览器控制台中收到运行时错误,提示“ Uncaught ReferenceError :猫未定义”。

为什么包含 es2015 加载程序会导致 require 函数停止工作?

webpack.config.js

var webpack = require('webpack');
var path = require('path');

var BUILD_DIR = path.resolve(__dirname, 'build');
var APP_DIR = path.resolve(__dirname, 'src/jsx');

module.exports = {
entry: APP_DIR + '/index.jsx',
output: {
path: BUILD_DIR,
filename: 'app.bundle.js',
},
module: {
loaders: [
{
test: /\.jsx$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel', // 'babel-loader' is also a valid name to reference
query: {
presets: ['es2015', 'react']
}
}
]
}
}

猫.jsx

var cats = ['dave', 'henry', 'martha'];
module.exports = cats;

index.jsx

cats = require('./cats.jsx');
console.log(cats);

import React from 'react';
import ReactDOM from 'react-dom';
import {render} from 'react-dom';

package.json

{
"name": "react-webpack",
"version": "1.0.0",
"description": "boilerplate for react and webpack",
"main": "index.html",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"license": "MIT",
"devDependencies": {
"babel-core": "^6.14.0",
"babel-loader": "^6.2.5",
"babel-preset-es2015": "^6.14.0",
"babel-preset-react": "^6.11.1",
"react": "^15.3.1",
"react-dom": "^15.3.1",
"webpack": "^1.13.2"
},
"private": "true",
"dependencies": {
"babel-core": "^6.14.0",
"babel-loader": "^6.2.5",
"babel-preset-es2015": "^6.14.0",
"babel-preset-react": "^6.11.1",
"react": "^15.3.1",
"react-dom": "^15.3.1"
}
}

最佳答案

我现在明白了,你有:

   cats = require('./cats.jsx');
console.log(cats);

应该是:

  var cats = require('./cats.jsx');
console.log(cats);

或者更好:

  const cats = require('./cats.jsx');
console.log(cats);

关于javascript - 在 webpack 中包含 "es2015"加载器配置规则会导致要求在运行时返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39581594/

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