Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CommonJS syntax and ES Module syntax to importReact #21

Open
oliver1204 opened this issue May 15, 2019 · 0 comments
Open

CommonJS syntax and ES Module syntax to importReact #21

oliver1204 opened this issue May 15, 2019 · 0 comments

Comments

@oliver1204
Copy link
Owner

oliver1204 commented May 15, 2019

在我们的项目中,我们用下面的方式去引入React:

import * as React from 'react';

export default class App extends React.Component<Props, State> {
  render() {
    return <h1>Hello {this.props.name}</h1>;
  }
}

因为我在查阅资料的时候发现很多地方也有下面的方式:

import React from 'react';

在我们的项目中,当我直接import React from 'react'这样写的时候,vs code 会报出下面的错误:

Module '"react"' has no default export.

为什么用 import * as React from 'react' 代替 import React from 'react'?

因为React 使用CommonJS 语法(module.exports = ...)而不是 ES Module 语法来导入。

如果你非常想使用import React from 'react',你可以在tsconfig.json 文件中 将allowSyntheticDefaultImports 这是为true, 然后你就可以正常的使用了。

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
  }
}

exports 和 module.exports 的区别

  1. module.exports 默认值为{}
  2. exports 是 module.exports 的引用
  3. exports 默认指向 module.exports 的内存空间
  4. require() 返回的是 module.exports 而不是 exports
  5. 若对 exports 重新赋值,则断开了 exports 对 module.exports 的指向

引用:

  • require 和 import 都可引用
//foo.js
exports.foo="foo"
//等同于
module.exports.foo="foo"

//bar.js
const { foo } = require('./foo.js')
console.log(foo);//'foo'
exports={
    foo: 'foo'
}

//bar.js
const { foo } = require('./foo.js')
//若对 exports 重新赋值,则断开了 exports 对 module.exports 的指向,
// reuqire 返回的是 module.exports 对象, 默认为 {}
console.log(foo);//undefined
@oliver1204 oliver1204 changed the title CommonJS syntax and ES Module syntax to improt React CommonJS syntax and ES Module syntax to importReact May 15, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant