Я пытаюсь извлечь определенные компоненты в своем приложении React в отдельную библиотеку компонентов многократного использования.
То, что я сделал, клонировано в этом проекте: https://rinsejs.io/ и впоследствии ссылается на githubрепо в моих основных проектах package.json
запись в пакете json основного проекта
"react-sharedlib": "git+ssh://git@github.com/myrepos/react-sharedlib.git#master",
Webpack.config внутри реагировать-sharedlib
// Path is in Node for free and will make simple resolving of directories no
// matter which part of your file system your library lives in
const path = require('path');
// Webpack is just a bunch of keys on module.exports!
module.exports = {
// This is where our app starts. This is why we hnpm install --save-dev babel-core@6.4.5ave done all this importing
// and exporting, to get to here
entry: './src/index.js',
// module (I know it's a bit weird to hanpm install --snpm install --save-dev babel-preset-es2015@6.3.13ave-dev babel-loader@6.2.1ve module.exports.module) is where we
// define all the rules for how webpack will deal with thing.
module: {
// rules takes an array, each item containing the respective rules
rules: [
{
// First up, our JavaScript rules.
// If you want to use the .jsx extension, you can change this line to
// test: /\.jsx?$/,
// The ? in the regex just means "optional"
test: /\.js$/,
// Don't bother spending time transpiling your installed packages
// exclude: /node_modules/,
// This is where we tell webpack to use babel to transpile our JS.
// The configuration can go here, but in this case it's in ./babelrc.js
use: {
loader: 'babel-loader',
},
},
{
// I haven't used SCSS in the base example, but it's here for you if you
// want! If you want to use CSS, you can change this next like's regex to
// /\.(css|scss)$/ or even just /\.css$/
test: /\.scss$/,
use: [
// These three libraries are commonly used together to turn Sass into
// CSS, then be able to load the CSS directly with imports. From there
// It gets put in the DOM for you.
{ loader: 'style-loader' },
{ loader: 'css-loader' },
{ loader: 'sass-loader' },
],
},
{
// Some image formats so you can import images
test: /\.(png|gif|jpg|svg)$/,
use: {
loader: 'url-loader',
options: {
limit: 50000,
},
},
},
],
},
// Here we define explicitly the file types we intend to deal with
resolve: {
extensions: ['.scss', '.js', '.json', '.png', '.gif', '.jpg', '.svg'],
},
// This is where we define how everything gets output.
// dist is a common output folder, and it should be gitignored. The build can
// be run after publishing so you don't wind up with it in source control
output: {
path: path.resolve(__dirname, 'dist/'),
publicPath: '',
// You can do fun things here like use the [hash] keyword to generate unique
// filenames, but for this purpose rinse.js is fine. This file and path will
// be what you put in package.json's "main" field
filename: 'rinse.js',
// This field determines how things are importable when installed from other
// sources. UMD may not be correct now and there is an open issue to fix this,
// but until then, more reading can be found here:
// https://webpack.js.org/configuration/output/#output-librarytarget
libraryTarget: 'umd',
},
};
Конфигурация Babel внутри общего ресурса-lib:
{
"presets": ["@babel/env", "@babel/preset-react", "es2015", "react"],
"plugins": ["@babel/plugin-syntax-dynamic-import"]
}
Package.JSON внутри shared-lib:
{
"name": "react-sharedlib",
"version": "1.0.0",
"description": "",
"main": "src/index.js",
"dependencies": {
"@babel/preset-react": "^7.0.0",
"babel-core": "^6.4.5",
"babel-loader": "^6.2.1",
"babel-preset-es2015": "^6.3.13"
},
"devDependencies": {
"@babel/plugin-syntax-dynamic-import": "^7.2.0",
"babel-preset-react": "^6.3.13"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/myrepos/react-sharedlib.git"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/myrepos/react-sharedlib/issues"
},
"homepage": "https://github.com/myrepos/react-sharedlib#readme"
}
Когда я пытаюсь построить свой проект, я получаю эту ошибку. (Что похоже на проблему с babel в какой-то степени, неспособность сослаться на синтаксис JSX или необходимость в настройке загрузчика. Кто-нибудь знает, что я делаю не так, или что еще можно попробовать? Как вы можете видеть из моегозависимости, которые я использовал при установке загрузчиков Babel, но безрезультатно. Я предполагаю, что мне просто не хватает части конфигурации, чтобы заставить ее распознавать HTML-код в файле JS.
ERROR in /Users/moi/git/usersection/user-section/node_modules/react-sharedlib/src/components/Button/Button.js 23:8
Module parse failed: Unexpected token (23:8)
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
| // along without changing any of the contents. This is basically just creating
| // a copy to pass along
> return <ButtonWrapper {...props}>{props.children}</ButtonWrapper>;
| }
|
@ /Users/moi/git/usersection/user-section/node_modules/react-sharedlib/src/components/Button/index.js 2:0-30 4:15-21
@ /Users/moi/git/usersection/user-section/node_modules/react-sharedlib/src/index.js
@ ./app/App.js
@ ./index.js
Последняя версия React btw. Webpack 4.29.6
Обновление: ** В соответствии с ответом, опубликованным ниже, мой файл общей библиотеки webpack.config.js теперь содержит эту запись, которая, к сожалению, не имеет значения.
rules: [
{
// First up, our JavaScript rules.
// If you want to use the .jsx extension, you can change this line to
// test: /\.jsx?$/,
// The ? in the regex just means "optional"
test: /\.js$/,
// Don't bother spending time transpiling your installed packages
// exclude: /node_modules/,
// This is where we tell webpack to use babel to transpile our JS.
// The configuration can go here, but in this case it's in ./babelrc.js
use: {
loader: 'babel-loader',
options: {
babelrcRoots: [".", "node_modules/react-sharedlib"]
}
},
}
ОСНОВНОЙ ПРОЕКТ .babelrc:
{
"presets": ["@babel/env", "@babel/preset-react"],
"plugins": ["@babel/plugin-syntax-dynamic-import"]
}
ОБЩИЙ ПРОЕКТ .babelrc:
{
"presets": ["@babel/env", "@babel/preset-react", "es2015", "react"],
"plugins": ["@babel/plugin-syntax-dynamic-import"]
}