我正在尝试使用react和webpack为应用程序设置样板代码。我能够通过webpack documentation获得webpack设置。接下来,我试图让Babel作为一个“加载器”来转换JSX。在上面的相同链接中有指示执行此操作但似乎文档不完整。除了上述说明之外,为了使反应起作用,我必须运行“npm install babel-preset-react”,然后在我的加载器配置中将“react”和“es2015”添加到查询参数中。但是,只要我添加“es2015”,我就开始在浏览器控制台中收到运行时错误,说“未捕获的参考错误:未定义猫”。
为什么包含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']
}
}
]
}
}
cats.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"
}
}
答案 0 :(得分:1)
我现在看到了,你有:
cats = require('./cats.jsx');
console.log(cats);
应该是:
var cats = require('./cats.jsx');
console.log(cats);
甚至更好:
const cats = require('./cats.jsx');
console.log(cats);