问题
I have a component that I want to publish in npm, I tested simply by importing it from the components folder in the project.
I managed to publish it, but now I get:
ERROR in ./node_modules/@//index.js Module parse failed: Unexpected token (11:8) You may need an appropriate loader to handle this file type.
My index.js is as follows:
import React from "react"
import Main from "./bootstrap/containers/main"
export default class BootstrapTable extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<Main {...this.props} changePage={(p) => this.props.changePage(p)}/>
)
}
}
Side note: I shouldn't need to change the webpack config as it should work as it is, like many other packages I am currently using.
回答1:
I solved it, thanks to @zerkms for the first step needed for my research.
Steps:
- Installed webpack and added the following config to webpack.config.js (my index.js is in ./src and externals are very important so you don't load instances of react):
var path = require('path'); module.exports = { mode: 'production', entry: './src/index.js', output: { path: path.resolve('dist'), filename: 'index.js', libraryTarget: 'commonjs2' }, module: { rules: [{ test: /\.js?$/, exclude: /(node_modules)/, use: { loader: 'babel-loader' } }] }, externals: { 'react': 'react', 'react-dom': 'react-dom', 'react-bootstrap': 'react-bootstrap' } }
- Created a .babelrc in the main folder with the following:
{ "presets": [ "react", "env", "stage-0" ] }
- Created an .npmignore file with:
src .babelrc webpack.config.js
- Created a package.json file with the following (your packages might be different but basically just install what you need "npm i package-name"):
{ "name": "@scope/package-name", "version": "1.0.0", "description": "My component", "main": "dist/index.js", "scripts": { "build": "webpack" }, "repository": { "type": "git", "url": "git+https://github.com/myrepo.git" }, "keywords": [ "react", "bootstrap" ], "author": "Me", "license": "MIT", "peerDependencies": { "react": "^16.4.0", "react-bootstrap": "^0.32.1", "react-dom": "^16.4.0" }, "devDependencies": { "react": "^16.4.0", "react-bootstrap": "^0.32.1", "react-dom": "^16.4.0", "babel-core": "^6.21.0", "babel-loader": "^7.1.4", "babel-preset-env": "^1.6.1", "babel-preset-react": "^6.16.0", "babel-preset-stage-0": "^6.24.1", "path": "^0.12.7", "webpack": "^4.5.0", "webpack-cli": "^2.0.14" } }
- npm install
- npm run build
- npm version 1.0.0 (increment for updates)
- npm publish
done!
These articles were great help:
- React + npm - How to Publish a React Component to npm
- How to create a React component and publish it on NPM
- A guide to building a React component with webpack 4, publishing to npm, and deploying the demo to GitHub Pages
来源:https://stackoverflow.com/questions/50710968/preparing-a-react-component-to-publish-on-npm