Rollup + Typescript: lib / index. js объединенные модули в конечном выводе - PullRequest
0 голосов
/ 30 марта 2020

Я создаю процесс сборки для библиотеки, которую мы опубликовали NPM. Мы переходим от веб-пакета к накопительному пакету для поддержки деревьев и поддержки ESM.

Проблема, с которой мы сталкиваемся, заключается в том, что когда мы анализируем финальный пакет, я точно вижу, что мы импортируем из узлов node_modules, для которых я не могу видеть то же самое главный индекс. js и наши собственные компоненты / файлы

Если я компилирую библиотеку только с использованием машинописного текста, это следующий вывод: TSC Compile output

tsconfig. json

{
  "include": ["src"],
  "exclude": [
    "lib",
    "**/*.stories.tsx",
    "**/*.stories.ts",
    "**/*.test.ts",
    "**/*.test.tsx",
    "**/__mocks__/*",
    "node_modules"
  ],
  "compilerOptions": {
    "noImplicitAny": false,
    "noImplicitReturns": false,
    "noImplicitThis": false,
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "target": "es5",
    "module": "ESNext",
    "moduleResolution": "node",
    "lib": ["es6", "dom", "es2016", "es2017"],
    "sourceMap": true,
    "declaration": true,
    "allowSyntheticDefaultImports": true,
    "outDir": "lib",
    "jsx": "react",
    "allowJs": false,
    "suppressImplicitAnyIndexErrors": true,
    "esModuleInterop": true
  }
}

Если я строю с использованием Rollup, это будет вывод:

Rollup Outcome

rollup.config. js

import pkg from './package.json';
import typescript from 'rollup-plugin-typescript2';
import commonjs from '@rollup/plugin-commonjs';
import resolve from '@rollup/plugin-node-resolve';
import external from 'rollup-plugin-peer-deps-external';
import { terser } from 'rollup-plugin-terser';

/**
 * Config tweaked from: https://www.pluralsight.com/guides/react-typescript-module-create
 */

export default {
  input: 'src/index.ts',
  output: [
    { file: pkg.main, format: 'cjs', sourcemap: true, exports: 'named' },
    { file: pkg.module, format: 'es', sourcemap: true, exports: 'named' },
  ],
  plugins: [
    external(), // prevents from bundling peer dependencies
    resolve(), // bundles third party dependencies we've installed in node_modules.
    typescript({
      rollupCommonJSResolveHack: true,
      clean: true,
    }),
    commonjs({
      // compiles js files into commonjs
      include: /node_modules/,
      namedExports: {
        'node_modules/react/react.js': ['Children', 'Component', 'PropTypes', 'createElement'],
        'node_modules/react-dom/index.js': ['render'],
        'node_modules/react-dates/index.js': [
          'DayPickerRangeController',
          'CalendarInfoPositionShape',
          'DateRangePicker',
          'SingleDatePicker',
        ],
        'node_modules/xss/lib/index.js': ['DEFAULT', 'whiteList'],
        'node_modules/uuid/index.js': ['v4'],
      },
    }),
    terser(), // uglify and minification of bundle
  ],
};

Я хочу быть в состоянии достичь первого результата (тот, который использует компилятор TS C), где я могу сохранить структуру проекта библиотеки, но используя процесс накопительной сборки, чтобы воспользоваться преимуществами Treehaking и процесс минимизации.

Чего мне не хватает в моей конфигурации?

1 Ответ

0 голосов
/ 31 марта 2020

вы можете попробовать, заменив файл вашего плагина на код, как показано ниже:

      nodeResolve({
        browser: true,
        dedup: ['react', 'react-dom'],
        extensions,
      }),
      postcss({
        extract: join(outputDir, 'index.css'),
        modules: {
          generateScopedName: cssScopeName,
        },
        namedExports: cssExportName,
        plugins: [
          postcssImport(),
        ],
      }),
      typescript({
        allowNonTsExtensions: true,
        useTsconfigDeclarationDir: true,
        objectHashIgnoreUnknownHack: true,
        tsconfigDefaults: {
          compilerOptions: {
            baseUrl: sourceDir,
            target: 'esnext',
            jsx: 'preserve',
            emitDecoratorMetadata: true,
            allowSyntheticDefaultImports: true,
            experimentalDecorators: true,
            paths: {
              [[pkg.name, "*"].join("/")]: [join(outputDir, pkg.name, "*")]
            }
            },
          }
      }),
      commonjs({
        include: [resolve(rootPath, 'node_modules/**')],
        exclude: [resolve(rootPath, 'node_modules/process-es6/**')],
        namedExports:{
          [resolve(rootPath, 'node_modules/react/index.js')]: [
            "Children",
            "Component",
            "PropTypes",
            "createRef",
            "useEffect",
            "useState",
            "useContext",
            "useRef",          ],
          [resolve(rootPath, "node_modules/react-dom/index.js")]: ["render", "findDOMNode"],
          [resolve(rootPath, "node_modules/react-is/index.js")]: ["isValidElementType"]
        },
      }),
      babel({
        babelrc: false,
        extensions,
        presets: [
          [ '@babel/preset-env', { modules: false } ],
          [ '@babel/preset-react' ],
        ],
      }),
......
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...