webpack#WebpackPluginInstance TypeScript Examples

The following examples show how to use webpack#WebpackPluginInstance. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: webpack.config.prod.ts    From vscode-sound-player with MIT License 6 votes vote down vote up
config = {
    mode: 'production',
    plugins: [
        new CleanWebpackPlugin()
    ],
    optimization: {
        minimize: true,
        minimizer: [new TerserPlugin({ extractComments: false }) as unknown as WebpackPluginInstance]
    }
} as Configuration
Example #2
Source File: webpack.config.prod.ts    From vscode-sound-player with MIT License 6 votes vote down vote up
config = {
    entry: {
        index: resolve(__dirname, '../src/index.tsx')
    },
    mode: 'production',
    plugins: [
        new CleanWebpackPlugin()
    ],
    optimization: {
        minimize: true,
        minimizer: [new TerserPlugin({ extractComments: false }) as unknown as WebpackPluginInstance]
    }
} as Configuration
Example #3
Source File: addWebpackPlugin.ts    From nextclade with MIT License 6 votes vote down vote up
export function addWebpackPlugin(
  nextConfig: NextConfig,
  plugin: WebpackPluginInstance | WebpackPluginFunction | ((this: Compiler, compiler: Compiler) => void) | any,
) {
  return addWebpackConfig(
    nextConfig,
    (nextConfig: NextConfig, webpackConfig: Configuration, { isServer }: WebpackConfigContext) => {
      if (!isServer) {
        if (webpackConfig?.plugins) {
          webpackConfig.plugins.push(plugin)
        } else {
          return { plugins: [plugin] }
        }
      }
      return webpackConfig
    },
  )
}
Example #4
Source File: LinkedPackageResolvePlugin.ts    From backstage with Apache License 2.0 5 votes vote down vote up
// Enables proper resolution of packages when linking in external packages.
// Without this the packages would depend on dependencies in the node_modules
// of the external packages themselves, leading to module duplication
export class LinkedPackageResolvePlugin implements WebpackPluginInstance {
  constructor(
    private readonly targetModules: string,
    private readonly packages: Package[],
  ) {}

  apply(resolver: any) {
    resolver.hooks.resolve.tapAsync(
      'LinkedPackageResolvePlugin',
      (
        data: {
          request: string;
          path?: false | string;
          context?: { issuer?: string };
        },
        context: unknown,
        callback: () => void,
      ) => {
        const pkg = this.packages.find(
          pkge => data.path && isChildPath(pkge.dir, data.path),
        );
        if (!pkg) {
          callback();
          return;
        }

        // pkg here is an external package. We rewrite the context of any imports to resolve
        // from the location of the package within the node_modules of the target root rather
        // than the real location of the external package.
        const modulesLocation = resolvePath(
          this.targetModules,
          pkg.packageJson.name,
        );
        const newContext = data.context?.issuer
          ? {
              ...data.context,
              issuer: data.context.issuer.replace(pkg.dir, modulesLocation),
            }
          : data.context;

        // Re-run resolution but this time from the point of view of our target monorepo rather
        // than the location of the external package. By resolving modules using this method we avoid
        // pulling in e.g. `react` from the external repo, which would otherwise lead to conflicts.
        resolver.doResolve(
          resolver.hooks.resolve,
          {
            ...data,
            context: newContext,
            path: data.path && data.path.replace(pkg.dir, modulesLocation),
          },
          `resolve ${data.request} in ${modulesLocation}`,
          context,
          callback,
        );
      },
    );
  }
}
Example #5
Source File: html.ts    From reskript with MIT License 5 votes vote down vote up
createHtmlPluginInstances = (buildContext: BuildContext): WebpackPluginInstance[] => {
    const {isDefaultTarget, buildTarget, entries} = buildContext;
    const createInstanceWithSuffix = createHTMLPluginWith(buildContext);
    const pluginsWithinTarget = entries.map(createInstanceWithSuffix('-' + buildTarget));
    const pluginsOfDefault = isDefaultTarget ? entries.map(createInstanceWithSuffix('')) : [];

    return [...pluginsWithinTarget, ...pluginsOfDefault];
}
Example #6
Source File: index.ts    From reskript with MIT License 5 votes vote down vote up
findHtmlWebpackPlugin = (compilation: Compilation) => {
    const isResolved = (plugin: WebpackPluginInstance) => {
        return plugin.constructor && plugin.constructor.name === 'HtmlWebpackPlugin';
    };

    const instance = (compilation.compiler.options.plugins || []).find(isResolved);
    return instance ? instance.constructor : null;
}
Example #7
Source File: webpack.config.ts    From bee-js with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
base = async (env?: Partial<WebpackEnvParams>): Promise<Configuration> => {
  const isProduction = process.env['NODE_ENV'] === 'production'
  const filename = env?.fileName || ['index.browser', isProduction ? '.min' : null, '.js'].filter(Boolean).join('')
  const entry = Path.resolve(__dirname, 'src')
  const path = Path.resolve(__dirname, 'dist')
  const plugins: WebpackPluginInstance[] = [
    new DefinePlugin({
      'process.env.ENV': process.env['NODE_ENV'] || 'development',
      'process.env.IS_WEBPACK_BUILD': 'true',
    }),
  ]

  return {
    bail: Boolean(isProduction),
    mode: (process.env['NODE_ENV'] as 'production') || 'development',
    devtool: isProduction ? 'source-map' : 'cheap-module-source-map',
    entry,
    output: {
      path,
      filename,
      sourceMapFilename: filename + '.map',
      library: 'BeeJs',
      libraryTarget: 'umd',
      globalObject: 'this',
    },
    module: {
      rules: [
        {
          test: /\.(ts|js)$/,
          // include: entry,
          use: {
            loader: 'babel-loader',
          },
        },
      ],
    },
    resolve: {
      extensions: ['.ts', '.js'],
      fallback: {
        path: false,
        fs: false,
        stream: false,
      },
    },
    optimization: {
      minimize: isProduction,
      minimizer: [
        // This is only used in production mode
        new TerserPlugin({
          terserOptions: {
            parse: {
              // we want terser to parse ecma 8 code. However, we don't want it
              // to apply any minfication steps that turns valid ecma 5 code
              // into invalid ecma 5 code. This is why the 'compress' and 'output'
              // sections only apply transformations that are ecma 5 safe
              // https://github.com/facebook/create-react-app/pull/4234
              ecma: 2018,
            },
            compress: {
              ecma: 5,
            },
            mangle: {
              safari10: true,
            },
            output: {
              ecma: 5,
              comments: false,
            },
          },
        }),
      ],
    },
    plugins,
    performance: {
      hints: false,
    },
  }
}
Example #8
Source File: transforms.ts    From backstage with Apache License 2.0 4 votes vote down vote up
transforms = (options: TransformOptions): Transforms => {
  const { isDev, isBackend } = options;

  const extraTransforms = isDev && !isBackend ? ['react-hot-loader'] : [];

  // This ensures that styles inserted from the style-loader and any
  // async style chunks are always given lower priority than JSS styles.
  // Note that this function is stringified and executed in the browser
  // after transpilation, so stick to simple syntax
  function insertBeforeJssStyles(element: any) {
    const head = document.head;
    // This makes sure that any style elements we insert get put before the
    // dynamic styles from JSS, such as the ones from `makeStyles()`.
    // TODO(Rugvip): This will likely break in material-ui v5, keep an eye on it.
    const firstJssNode = head.querySelector('style[data-jss]');
    if (!firstJssNode) {
      head.appendChild(element);
    } else {
      head.insertBefore(element, firstJssNode);
    }
  }

  const loaders = [
    {
      test: /\.(tsx?)$/,
      exclude: /node_modules/,
      loader: require.resolve('@sucrase/webpack-loader'),
      options: {
        transforms: ['typescript', 'jsx', ...extraTransforms],
        disableESTransforms: true,
        production: !isDev,
      },
    },
    {
      test: /\.(jsx?|mjs|cjs)$/,
      exclude: /node_modules/,
      loader: require.resolve('@sucrase/webpack-loader'),
      options: {
        transforms: ['jsx', ...extraTransforms],
        disableESTransforms: true,
        production: !isDev,
      },
    },
    {
      test: /\.(js|mjs|cjs)/,
      resolve: {
        fullySpecified: false,
      },
    },
    {
      test: [/\.icon\.svg$/],
      use: [
        {
          loader: require.resolve('@sucrase/webpack-loader'),
          options: {
            transforms: ['jsx', ...extraTransforms],
            disableESTransforms: true,
            production: !isDev,
          },
        },
        {
          loader: require.resolve('@svgr/webpack'),
          options: { babel: false, template: svgrTemplate },
        },
      ],
    },
    {
      test: [
        /\.bmp$/,
        /\.gif$/,
        /\.jpe?g$/,
        /\.png$/,
        /\.frag/,
        { and: [/\.svg/, { not: [/\.icon\.svg/] }] },
        /\.xml/,
      ],
      type: 'asset/resource',
      generator: {
        filename: 'static/[name].[hash:8].[ext]',
      },
    },
    {
      test: /\.(eot|woff|woff2|ttf)$/i,
      type: 'asset/resource',
      generator: {
        filename: 'static/[name].[hash][ext][query]',
      },
    },
    {
      test: /\.ya?ml$/,
      use: require.resolve('yml-loader'),
    },
    {
      include: /\.(md)$/,
      type: 'asset/resource',
      generator: {
        filename: 'static/[name].[hash][ext][query]',
      },
    },
    {
      test: /\.css$/i,
      use: [
        isDev
          ? {
              loader: require.resolve('style-loader'),
              options: {
                insert: insertBeforeJssStyles,
              },
            }
          : MiniCssExtractPlugin.loader,
        {
          loader: require.resolve('css-loader'),
          options: {
            sourceMap: true,
          },
        },
      ],
    },
  ];

  const plugins = new Array<WebpackPluginInstance>();

  if (isDev) {
    plugins.push(new webpack.HotModuleReplacementPlugin());
  } else {
    plugins.push(
      new MiniCssExtractPlugin({
        filename: 'static/[name].[contenthash:8].css',
        chunkFilename: 'static/[name].[id].[contenthash:8].css',
        insert: insertBeforeJssStyles, // Only applies to async chunks
      }),
    );
  }

  return { loaders, plugins };
}
Example #9
Source File: webpack.config.ts    From swarm-cli with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
base = (env?: Partial<WebpackEnvParams>): Configuration => {
  const isProduction = env?.mode === 'production'
  const filename = env?.fileName || ['index.js'].filter(Boolean).join('')
  const entry = Path.resolve(__dirname, 'src')
  const path = Path.resolve(__dirname, 'dist')
  const target = 'node'
  const plugins: WebpackPluginInstance[] = [
    new DefinePlugin({
      'process.env.ENV': env?.mode || 'development',
      'process.env.IS_WEBPACK_BUILD': 'true',
    }),
    new BannerPlugin({ banner: '#!/usr/bin/env node', raw: true }),
  ]

  return {
    bail: Boolean(isProduction),
    mode: env?.mode || 'development',
    devtool: isProduction ? false : 'cheap-module-source-map',
    entry,
    output: {
      path,
      filename,
      sourceMapFilename: filename + '.map',
      library: PackageJson.name,
      libraryTarget: 'umd',
      globalObject: 'this',
    },
    module: {
      rules: [
        {
          test: /\.(ts|js)$/,
          // include: entry,
          use: {
            loader: 'babel-loader',
          },
        },
      ],
    },
    resolve: {
      extensions: ['.ts', '.js'],
      fallback: {
        path: false,
        fs: false,
      },
    },
    optimization: {
      minimize: isProduction,
      minimizer: [
        // This is only used in production mode
        new TerserPlugin({
          terserOptions: {
            parse: {
              // we want terser to parse ecma 8 code. However, we don't want it
              // to apply any minfication steps that turns valid ecma 5 code
              // into invalid ecma 5 code. This is why the 'compress' and 'output'
              // sections only apply transformations that are ecma 5 safe
              // https://github.com/facebook/create-react-app/pull/4234
              ecma: 2018,
            },
            compress: {
              ecma: 5,
            },
            mangle: {
              safari10: true,
            },
            output: {
              ecma: 5,
              comments: false,
            },
          },
          // Use multi-process parallel running to improve the build speed
          // Default number of concurrent runs: os.cpus().length - 1
          parallel: true,
        }),
      ],
    },
    plugins,
    target,
    node: {
      global: true,
      __filename: 'mock',
      __dirname: 'mock',
    },
    performance: {
      hints: false,
    },
    watch: !isProduction,
  }
}