How to mix Angular Elements with the “ng g library” approach?

久未见 提交于 2019-12-02 20:26:07

ng build internally use webpack to do the building. So this problem actually breaks down to two parts.

  1. Without ng eject, how to tap into the internal webpackConfig and customize it to our need.
  2. What does desired webpackConfig look like for this use case.

For part 1, there's a solution @angular-builders/custom-webpack out there. Basically it allow you to merge some extra field into the internal webpackConfig, and still use the offical "@angular-devkit/build-angular:browser" as builder.

Now for part 2, your use case is simply a multi-entry-multi-output build problem in webpack. The solution is quite straight forward.

const partialWebpackConfig = {
  entry: {
    'custom/comp1': '/path/to/src/lib/custom/comp1.ts',
    'custom/comp2': '/path/to/src/lib/custom/comp2.ts',
  },
  output: {
    path: path.resolve(__dirname, 'Dist'),
    filename: '[name].js'
  }
}

Below is a step-by-step instruction to setup this config.

  1. npm install @angular-builders/custom-webpack
  2. create a webpack.config.js in your project root:
const path = require('path');
module.exports = {
  entry: {
    'custom/comp1': path.resolve(__dirname, 'src/lib/custom/comp1.ts'),
    'custom/comp2': path.resolve(__dirname, 'src/lib/custom/comp2.ts')
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js'
  }
}
  1. edit "architect.build" field in angular.json:
{
  // ...
  "architect": {
    "build": {
      "builder": "@angular-builders/custom-webpack:browser",
      "options": {
        "customWebpackConfig": {
          "path": "./webpack.config.js",
        },
        // ...
  1. run ng build, should see the result.

For advance usage, it's worth mentioning that @angular-builders/custom-webpack support exporting webpack config as a function to gain full control of the final webpackConfig used.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!