13、先来试试hooks模式
1、index.tsx 修改引用的文件, 改成引用hooks模式的
export { default as Example } from './example/index';
2、重新打包,这里可以直接把打包好的文件复制到目标项目node_modules下的对应包文件,为了快速测试
3、需要重启实际项目,这时候发现报错
Uncaught Error: Minified React error #321; visit https:
或者
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
笔者这里来回调试可能报错不一样,
4、修改webpack.prod.config.js
添加如下代码
externals: {
react: {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react'
},
'react-dom': {
root: 'ReactDOM',
commonjs2: 'react-dom',
commonjs: 'react-dom',
amd: 'react-dom'
}
},
重新打包,发现这时候的打包文件很小了,没有了react包,复制到目标文件,重启,发现恢复正常
5、这是为什么哪????
这是由于打包的时候也打包了一份react和react-dom
这种解决方法其实就是让npm安装的组件使用项目中的react
14、打包样式
需要使用mini-css-extract-plugin 提取css
1、完整的配置文件如下,添加了MiniCssExtractPlugin 插件
const path = require('path')
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
mode: 'production',
entry: path.resolve(__dirname, '../src/components/index.tsx'), // 指定开发入口文件
output: {
filename: 'yoai.component.js', // 打包后的文件名称
path: path.resolve(__dirname, '../dist'), // 输出路径
libraryTarget: 'commonjs2',
library: 'dragon-mobile'
},
externals: {
react: {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react'
},
'react-dom': {
root: 'ReactDOM',
commonjs2: 'react-dom',
commonjs: 'react-dom',
amd: 'react-dom'
}
},
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: 'dragon.mobile.css'
}),
],
resolve: {
// 解决导入的文件可以不用添加后缀名
extensions: ['.tsx', '.ts', 'jsx', '.js'],
},
module: {
rules: [
{
test: /\.(j|t)sx?$/,
exclude: /node_modules/,
use: {
loader: 'ts-loader',
options: {
// transpileOnly: true
}
}
},
{
test: /\.s[ac]ss$/i,
use: [
{
loader: MiniCssExtractPlugin.loader
},
{
loader: 'css-loader',
options: {
sourceMap: true //是否打开样式查找
}
},
// Compiles Sass to CSS
{
loader: 'sass-loader', // 解析样式文件
options: {
sourceMap: true
}
}
]
}
]
}
}
注意 rules的样式配置和开发是不一样的,这个时候就不需要style-loader了,plugins的配置
2、写一个样式,components/index.tsx 引入
我这里是这样
import '../scss/styles.scss'
styles.scss
.wrap{
background: red;
height: 100px;
width: 100px;
text-align: center;
line-height: 100px;
margin: 0 auto;
cursor: pointer;
font-size: 20px;
color: #ffffff;
}
3、打包发现dist文件夹多了一个dragon.mobile.css 文件
4、重新npm publish,目标项目重新安装依赖,导入样式
import 'dragon-mobile/dist/dragon.mobile.css'
5、ok完成操作
这个时候我们就算大功告成!!!已经完整的开发发布了一个React项目,但是现在的项目还不是完美的,还有很大的优化空间,接下来我会继续完善项目配置,package.json的规范以及各个流程的完善,按需加载等等,期待下一章吧