从零开始搭建react组件并且发布npm(二)

644 阅读2分钟

7、样式配置

7.1、npm i sass sass-loader style-loader css-loader -D

{
    test: /\.s[ac]ss$/i,
    use: [
        // Creates `style` nodes from JS strings
        'style-loader',
        // Translates CSS into CommonJS
        {
            loader: 'css-loader',
            options: {
              sourceMap: true //是否打开样式查找
            }
        },
          // Compiles Sass to CSS
        {
            loader: 'sass-loader', // 解析样式文件
            options: {
              sourceMap: true
            }
        }
    ]
}
7.2、src下添加index.scss

$color: red;
.wrap{
  background: $color;
  height: 1000px;
  width: 100px;
}
7.3 App.jsx 添加
import './index.scss'

添加class <div className='wrap'>Hello World</div>

ok!!! 样式也好了

⚠️其实此时我们完全可以开始开发了,开发环境已经配置完成,配置一下打包就行,但是写组件嘛,完整一点,使用一下Typescript

8、改成 Typescript

8.1、npm i ts-loader typescript -D 

8.2、跟目录下面添加tsconfig.json 内容先填写
tsconfig.json是 Ts的配置
{
  "compilerOptions": {
      "outDir": "./dist/",
      "sourceMap": true,
      "noImplicitAny": true,
      "strictNullChecks": true,
      "module": "es6",
      "target": "es5",
      "jsx": "react",
      "allowJs": true,
      "moduleResolution": "node",
      "allowSyntheticDefaultImports": true
  },
  "includes": [
    "./src/",
  ]
}

8.3、修改webpack.dev.config.js 匹配js的规则如下

{
    test: /\.(j|t)sx?$/,
    exclude: /node_modules/,
    use: {
        loader: "ts-loader",
        options: {
        // transpileOnly: true
        }
    }
}

8.4、重启命令,发现报错
TS7016: Could not find a declaration file for module 'react'

TS7026: JSX element implicitly has type 'any' because no interface 'JSX.IntrinsicElements' exists

因为我们还要添加React和React-DOM以及它们的声明文件到package.json文件里做为依

8.5、 npm i @types/react @types/react-dom -D

这时可以开始使用了,修改App.tsx

import React, { Component } from 'react'
import './index.scss'

type State = {
  name: string;
  age: number
}

type Props = {

}

export default class App extends Component<Props, State> {
  constructor(props: Props) {
    super(props)
    this.state = {
      name: 'React',
      age: 6
    }
  }

  render() {
    return (
      <div className='wrap'>Hello World</div>
    )
  }
}


或者使用hooks模式

import React, { useState } from 'react'
import './index.scss'
type Props = {
  text: string
  age?: number
}

const App = (props: Props) => {
  const [name, setName] = useState<string>('');
  const { text } = props
  
  const a = () => {
  }

  return (
    <div className='wrap' onClick={a}>Hello World</div>
  )
}

export default App


还是稍微有点瑕疵,感觉还不是特别的强制,之后逐渐的优化

9、添加eslint配置

代码规范怎么能少了eslint

9.1、npm install eslint -D
9.2、根目录添加.eslintrc.js
先添加内容
module.exports = 
  {
    'rules': {
      'quotes': [2, 'single'],
      'space-infix-ops': ['error', {'int32Hint': false}],
      'indent': ['error', 2],
      'key-spacing': ['error', { 'beforeColon': false }],
      'lines-between-class-members': ['error', 'always'],
      'no-redeclare': 'error',
      'comma-spacing': ['error', { 'before': false, 'after': true }],
      'no-unneeded-ternary': 'error'
    }
  }
这时候发现代码并没有提示格式的信息,这是因为这里用的是ts,

9.3、 npm i @typescript-eslint/eslint-plugin @typescript-eslint/parser  eslint-plugin-react -D
由于我们要使用React新特性 Hooks,

@typescript-eslint/parser:将 TypeScript 转换为 ESTree,使 eslint 可以识别
@typescript-eslint/eslint-plugin:只是一个可以打开或关闭的规则列表


.eslintrc.js 修改如下,之后的rules再根据实际情况填写

module.exports = {
  parser: '@typescript-eslint/parser',
  extends: [
    'plugin:@typescript-eslint/recommended',
  ],
  plugins: ['@typescript-eslint', 'react'],
  rules: {
    quotes: [2, 'single'],
    'react/jsx-uses-react': 2
  },
};

开发环境基本OK了,接下来我们写一个组件,配置生产环境打包