gpt4 book ai didi

javascript - Webpack 错误无法解析文件或目录(React)

转载 作者:行者123 更新时间:2023-11-28 05:12:02 24 4
gpt4 key购买 nike

当所有组件都在同一个文件中时,Webpack 可以正常工作。当我尝试将每个组件分离到他自己的文件中时,出现错误:

'module not found: error: cannot resolve file or directory'.

我使用的是 Windows 10。

文件夹结构:

 reacttest (root)
node_modules
public
components
GreeterMassage.jsx
app.jsx
bundle.js
index.html
package.json
server.js
webpack.config.js

app.jsx 代码:

  const React = require('react');
const ReactDOM = require('react-dom');
const GreeterMassage = require('./components/GreeterMassage');

const GreeterForm = React.createClass({
onFormSubmit: function(e) {
e.preventDefault();

const updates = {}
const name = this.refs.name.value;
const massage = this.refs.massage.value;

if(name.length > 0) {
this.refs.name.value = '';
updates.name = name;
}
if(massage.length > 0) {
this.refs.massage.value = '';
updates.massage = massage;
}
this.props.onNewData(updates);
},
render: function() {
return (
<form onSubmit={this.onFormSubmit}>
<div>
<input type="text" ref="name" placeholder="Name"/>
</div>
<div>
<textArea type="text" ref="massage" placeholder="Massage"/>
</div>
<div>
<button>Set</button>
</div>
</form>
);
}
});

const Greeter = React.createClass({
getDefaultProps: function() {
return {
name: 'React',
massage: 'Default massage'
};
},
getInitialState: function() {
return {
name: this.props.name,
massage: this.props.massage
};
},
handleNewData: function(updates) {
this.setState(updates);
},
render: function() {
const name = this.state.name;
const massage = this.state.massage;
return (
<div>
<GreeterMassage name={name} massage={massage}/>
<GreeterForm onNewData={this.handleNewData}/>
</div>
);
}
});

const firstname = 'My First Name';

ReactDOM.render(
<Greeter name={firstname}/>,
document.getElementById('app')
);

GreeterMassage.jsx 代码:

    const React = require('react');

const GreeterMassage = React.createClass({
render: function() {
const name = this.props.name;
const massage = this.props.massage;
return (
<div>
<h1>Hello {name}</h1>
<p>{massage}</p>
</div>
);
}
});

module.exports = GreeterMassage;

webpack.config.js

    module.exports = {
entry: './public/app.jsx',
output: {
path: __dirname,
filename: './public/bundle.js'
},
resolve: {
extesions: ['', '.js', '.jsx']
},
module: {
loaders: [
{
loader: 'babel-loader',
query: {
presets: ['react', 'es2015']
},
test: /\.jsx?$/,
exclude: /(node_modules | bower_components)/
}
]
}
};

最佳答案

app.jsxGreeterMassage.jsx 位于同一目录中,并且导入是相对于执行导入的文件,因此应该是:

const GreeterMassage = require('./GreeterMassage');

关于javascript - Webpack 错误无法解析文件或目录(React),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41291993/

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