【问题标题】:Can webpack handle require() correctly?webpack 可以正确处理 require() 吗?
【发布时间】: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.exportsrequire。然而,奇怪的是,以下工作完美。

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 中使用 requiremodule.exports 是否存在细微差别,但尚未完全实现?

【问题讨论】:

  • 您遇到的错误是什么?读者如何重现您看到的内容?
  • 只是尝试使用堆栈溢出编辑器...它阻止我发布我的整个帖子,声称其中一些不是代码时应该格式化为代码。
  • 这真的很奇怪,所见即所得一直在抱怨我需要将帖子的自然语言部分格式化为代码。现在似乎工作正常。

标签: webpack require


【解决方案1】:

现在可以使用了。问题出在config.js 文件中。当我改变时:

const debugStyleConfig = {
    ...baseConfig,
    useArrowKeysToCycleViews: true
};

const debugStyleConfig = {
    useArrowKeysToCycleViews: true
};

...错误消失了。我相信这可能是 nodeJS 不支持 Object.assign 速记 / 对象扩展运算符的结果。但它这样做而不是引发语法错误有点麻烦。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-24
    • 2015-11-19
    • 1970-01-01
    • 1970-01-01
    • 2014-08-03
    • 1970-01-01
    • 2017-09-07
    • 2012-08-07
    相关资源
    最近更新 更多