【发布时间】:2019-11-25 14:02:12
【问题描述】:
我了解 Webpack 允许用户使用 es6 模块语法、AMD 或 commonJS 导入和导出模块。但是,在处理 webpack 项目时,简单的 require 语句会引发错误。
这是在新创建的“create-react-app”项目的上下文中。
config.js
const packageJson = require('../package.json');
const baseConfig = {
urls: {
base: packageJson.homepage,
engineServer: 'localhost:3001'
},
useArrowKeysToCycleViews: false
};
const debugStyleConfig = {
...baseConfig,
useArrowKeysToCycleViews: true
};
module.exports = { // <-- IMPORTANT
config: debugStyleConfig
};
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App/App';
import * as serviceWorker from './serviceWorker';
import './boot'; // <-- IMPORTANT
ReactDOM.render(<App />, document.getElementById('root'));
serviceWorker.unregister();
boot.js
// The following line...
import { config } from './config';
// ... raises this error:
// Attempted import error: 'config' is not exported from './config'.
// If the following line is used instead...
// const { config } = require('./config');
// ...a different error is raised:
// TypeError: Cannot assign to read only property 'exports' of object '#<Object>'
为了理解这个问题,我创建了第二个项目,它使用了module.exports 和require。然而,奇怪的是,以下工作完美。
foo.js
function foo() {
return 'fooz';
}
function bar() {
return 'bar';
}
module.exports = {
foo, bar
};
App.js
import React from 'react';
import './App.css';
const { foo, bar } = require('./foo');
function App() {
return (
<div className="App">
<h1>{foo()}</h1>
<h1>{bar()}</h1>
</div>
);
}
export default App;
在 webpack 中使用 require 和 module.exports 是否存在细微差别,但尚未完全实现?
【问题讨论】:
-
您遇到的错误是什么?读者如何重现您看到的内容?
-
只是尝试使用堆栈溢出编辑器...它阻止我发布我的整个帖子,声称其中一些不是代码时应该格式化为代码。
-
这真的很奇怪,所见即所得一直在抱怨我需要将帖子的自然语言部分格式化为代码。现在似乎工作正常。