Javascript webpack: import + module.exports 在同一个模块中导致错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42449999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
webpack: import + module.exports in the same module caused error
提问by juniorgarcia
I'm developing a website with webpack. When I have a code like this:
我正在用 webpack 开发一个网站。当我有这样的代码时:
import $ from 'jquery';
function foo() {};
module.exports = foo;
I got the error Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>'.
我得到了错误Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>'。
Turns out that changing import $ from 'jquery'to var $ = require('jquery')don't cause any errors.
事实证明,更改import $ from 'jquery'为var $ = require('jquery')不会导致任何错误。
Why import with module.exports causes this error? Is anything wrong in using require instead?
为什么使用 module.exports 导入会导致此错误?使用 require 有什么问题吗?
回答by Matthew Herbst
You can't mix importand module.exports. In the importworld, you need to export things.
你不能混合import和module.exports。在import世界上,你需要出口东西。
// Change this
module.exports = foo;
// To this
export default foo;
回答by Emmanuel Mahuni
This happens if other modules down stream have an unexpected require tree. Babel changes require to import where it isn't supposed to which causes the aforementioned issue @Matthew Herbst. To solve this add "sourceType": "unambiguous"to your babelrcfile or babel.config.js so that @babel/plugin-transform-runtime won't do this change of require expression to import in your commonjs files. eg:
如果下游的其他模块有意外的需求树,就会发生这种情况。Babel 更改需要导入它不应该导入的位置,这会导致上述问题@Matthew Herbst。要解决此问题,请添加"sourceType": "unambiguous"到您的babelrc文件或 babel.config.js 中,以便 @babel/plugin-transform-runtime 不会执行此更改 require 表达式以导入您的 commonjs 文件。例如:
module.exports = {
presets: [
'@quasar/babel-preset-app'
],
"sourceType": "unambiguous"
}

