使用 Rollup 构建 Nx 库不会捆绑所需的依赖项

Mik*_*ing 8 javascript rollup webpack nrwl-nx

问题

我使用默认的 Rollup 执行器来构建一个 Nx 库,稍后我将在类似浏览器的环境中运行该库。生成的包不能包含imports 或requires。运行nx run ssr-bundle:build应该创建一个包含我的应用程序代码和依赖项的单个包。

如何捆绑我的所有代码,以便我的imported 代码位于同一个文件中?

例子

源文件index.ts

import { isBoolean } from 'lodash';

async function handler() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(isBoolean);
    }, 1000);
  });
}

export default handler;
Run Code Online (Sandbox Code Playgroud)

输出文件index.cjs.js

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var lodash = require('lodash'); <--------- this should be the lodash source code

async function handler() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(lodash.isBoolean);
    }, 1000);
  });
}

exports["default"] = handler;
Run Code Online (Sandbox Code Playgroud)

mpm*_*yre 0

卷起:

多入口插件

rollup.config.js

import multi from '@rollup/plugin-multi-entry';

export default {
  input: ['batman.js', 'robin.js', 'joker.js'],
  output: {
    dir: 'output'
  },
  plugins: [multi()]
};
Run Code Online (Sandbox Code Playgroud)

Webpack:使用 webpack 并指定单个输出文件。

Webpack.config.js 简单示例:

const path = require("path");

module.exports = {
  // Specify the entry point of your application
  entry: path.resolve(__dirname, "./src/index.tsx"),
  // Specify the output path and name
  output: {
    path: path.resolve(__dirname, "../build/"),
    filename: 'bundle.js',
  },
};
Run Code Online (Sandbox Code Playgroud)

如果您有多个文件未在入口点内导入并且需要多个文件(或块)

module.exports = {
  entry: {
    app: './src/app.js',
    search: './src/search.js',
  },
  output: {
    filename: '[name].js',
    path: __dirname + '/dist',
  },
};
Run Code Online (Sandbox Code Playgroud)

如果你想要一个文件:

module.exports = {
  entry: {
    app: './src/app.js',
    search: './src/search.js',
  },
  output: {
    filename: 'bundle.js',
    path: __dirname + '/dist',
  },
};
Run Code Online (Sandbox Code Playgroud)

在这里阅读更多内容