Я использую Rollup для объединения ряда компонентов React. Компоненты стилизованы с использованием стилизованные компоненты. Я включил styled-components, react и некоторые другие пакеты в массив options.external.
Когда я импортирую свои компоненты в другое приложение, у меня появляется ошибка, в которой говорится, что styled-components создается дважды на странице. Мне кажется, что это проблема, связанная с моей конфигурацией накопительного пакета или самим накопительным пакетом, потому что при запуске процесса сборки я получаю какие-то непонятные результаты.
Файл конфигурации / сборки накопительного пакета:
const babel = require('rollup-plugin-babel');
const commonjs = require('rollup-plugin-commonjs');
const nodeResolve = require('rollup-plugin-node-resolve');
const replace = require('rollup-plugin-replace');
const sass = require('rollup-plugin-sass');
const autoprefixer = require('autoprefixer');
const path = require('path');
const rollup = require('rollup');
const cwd = process.cwd();
const { name, moduleName } = require(path.join(cwd, 'package.json'));
const build = opts => {
rollup
.rollup({
input: opts.input || 'src/index.js',
external: [
'react',
'react-proptypes',
'styled-components',
],
output: {
globals: {
'react': 'React',
'react-proptypes': 'PropTypes',
'styled-components': 'styled',
}
},
globals: {
'react': 'React',
'react-proptypes': 'PropTypes',
'styled-components': 'styled',
},
plugins: [
babel({
exclude: 'node_modules/**',
plugins: ['external-helpers']
}),
sass({
insert: false,
output: false,
include: '**/*.scss',
exclude: [],
options: {
importer( url /*, prev */ ) {
if ( url.startsWith( '~' ) ) {
const path = process.cwd() + '/node_modules/' + url.slice( 1 );
return {
file: path
};
}
}
}
}),
nodeResolve({
jsnext: true
}),
commonjs({
include: 'node_modules/**',
namedExports: {
'./node_modules/react/react.js': [
'cloneElement',
'createElement',
'PropTypes',
'Children',
'Component'
]
}
}),
replace({
'process.env.NODE_ENV': JSON.stringify('production')
})
]
})
.then(bundle => {
const format = opts.format || 'umd';
const formatMod = opts.formatMod || format;
const exports = opts.exports || 'named';
const dest = `dist/${name}.${formatMod}.js`;
console.info(dest);
bundle.write({
exports,
format,
name: moduleName || name,
file: dest
});
})
.catch(err => {
console.error(err);
});
};
build({
format: 'umd'
});
build({
format: 'es',
formatMod: 'esm'
});
build({
format: 'cjs'
});
Простой компонент:
import React from 'react';
import styled from 'styled-components';
const StyledTest = styled.div`
font-size: 24px;
color: red;
font-family: sans-serif;
`;
const Test = ({ children }) => (
<StyledTest>{children}</StyledTest>
);
export default Test;
Скомпилированный простой компонент:
import React from 'react';
import styled from 'styled-components';
var taggedTemplateLiteral = function (strings, raw) {
return Object.freeze(Object.defineProperties(strings, {
raw: {
value: Object.freeze(raw)
}
}));
};
var _templateObject = taggedTemplateLiteral(['\n font-size: 24px;\n color: red;\n font-family: sans-serif;\n'], ['\n font-size: 24px;\n color: red;\n font-family: sans-serif;\n']);
var StyledTest = styled.div(_templateObject);
var Test = function Test(_ref) {
var children = _ref.children;
return React.createElement(
StyledTest,
null,
children
);
};
export default Test;
Непонятные ошибки, которые я наблюдаю в Rollup, следующие:
The following options have been renamed — please update your config: globals -> output.globals
The following options have been renamed — please update your config: globals -> output.globals
The following options have been renamed — please update your config: globals -> output.globals
dist/@vz-react/test.umd.js
dist/@vz-react/test.esm.js
dist/@vz-react/test.cjs.js
No name was provided for external module 'react' in options.globals – guessing 'React'
No name was provided for external module 'styled-components' in options.globals – guessing 'styled'
Несмотря на то, что options.globals и options.output.globals определены, я вижу эти ошибки. Если я удалю options.globals, я больше не получаю сообщение об ошибке с просьбой переместить options.globals в options.output.globals, но я все равно получаю сообщение об ошибке ниже.
Версии пакета:
"rollup": "^0.59.4",
"styled-components": "^3.2.5",



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Перечитав (FAQ по стилизованным компонентам) [https://www.styled-components.com/docs/faqs#why-am-i-getting-a-warning-about-several-instances-of-module-on-the-page], я понял, что у меня есть дублированный модуль styled-components.
Я решил проблему, добавив в конфигурацию своего веб-пакета следующее:
resolve: {
+ modules: [path.resolve(appFolder, 'node_modules'), 'node_modules'],
}
Я все еще не уверен, почему я получаю эти предупреждения от Rollup, но проблема со стилизованными компонентами больше не является проблемой.
???
Я объявил свои внешние элементы следующим образом:
const externals = {
'react' : 'React',
'react-dom' : 'ReactDOM',
'react-scripts' : 'ReactScripts',
};
затем добавьте ключи переменной в экспорт по умолчанию вашей конфигурации накопления.
external: Object.keys(externals),
Это должно помочь вам избавиться от предупреждения (: