我正在尝试将React组件创建为npm软件包,并且正在关注此链接https://medium.com/quick-code/publish-your-own-react-component-as-npm-package-under-5-minutes-8a47f0cb92b9,对此我还很陌生。
这是我在运行npm.start时遇到的错误
ERROR in ./src/index.js 6:4
Module parse failed: Unexpected token (6:4)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| const { width, height, color, text } = props;
| return (
> <div
| style={{
| width: width || 100,
我在网上看了看,似乎与webpack.config出现了问题,但是我不确定在我的哪里出错了。
这些是我的文件
webpack.config
var path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'index.js',
libraryTarget: 'commonjs2'
},
module: {
rules: [
{
test: /\.js$/,
include: path.resolve(__dirname, 'src'),
exclude: /(node_modules|bower_components|build)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
}
]
},
externals: {
'react': 'commonjs react'
}
};
.babelrc
{
"presets": ["env"],
"plugins": [
"transform-object-rest-spread",
"transform-react-jsx"
]
}
src / index.js
import React from "react";
const ReactColorSquare = props => {
const { width, height, color, text } = props;
return (
<div
style={{
width: width || 100,
height: height || 100,
backgroundColor: color || "blue"
}}
>
{text}
</div>
);
};
export default ReactColorSquare;
package.json
{
"name": "reactnpmpackage",
"version": "1.0.0",
"description": "",
"main": "build/index.js",
"scripts": {
"start": "webpack --watch",
"build": "webpack",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"react": "^16.13.1",
"webpack": "^4.43.0"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-loader": "^8.1.0",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-plugin-transform-react-jsx": "^6.24.1",
"babel-preset-env": "^1.7.0",
"webpack-cli": "^3.3.11"
}
}
这是我的项目结构
请问我在哪里弄错了。.
答案 0 :(得分:0)
尝试使用@babel/preset-react
。执行npm i --save-dev @babel/preset-react
,然后将其添加到您的.babelrc文件中:
// .babelrc
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
],
"plugins": [
"transform-object-rest-spread",
"transform-react-jsx"
]
}
您也可以尝试将libraryTarget
更改为通用模块定义:
libraryTarget: 'umd'
或在webpack.config中将mode: development
添加到您的module.exports
。
这为我解决了几次类似的问题。