webpack#DefinePlugin TypeScript Examples

The following examples show how to use webpack#DefinePlugin. 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-configuration-change.service.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
private globalVariableChange() {
    const defineObject: Record<string, string> = {
      global: `${this.buildPlatform.globalObject}.__global`,
      window: `${this.buildPlatform.globalVariablePrefix}`,
      globalThis: `${this.buildPlatform.globalVariablePrefix}`,
      Zone: `${this.buildPlatform.globalVariablePrefix}.Zone`,
      setTimeout: `${this.buildPlatform.globalVariablePrefix}.setTimeout`,
      clearTimeout: `${this.buildPlatform.globalVariablePrefix}.clearTimeout`,
      setInterval: `${this.buildPlatform.globalVariablePrefix}.setInterval`,
      clearInterval: `${this.buildPlatform.globalVariablePrefix}.clearInterval`,
      setImmediate: `${this.buildPlatform.globalVariablePrefix}.setImmediate`,
      clearImmediate: `${this.buildPlatform.globalVariablePrefix}.clearImmediate`,
      Promise: `${this.buildPlatform.globalVariablePrefix}.Promise`,
      Reflect: `${this.buildPlatform.globalVariablePrefix}.Reflect`,
      requestAnimationFrame: `${this.buildPlatform.globalVariablePrefix}.requestAnimationFrame`,
      cancelAnimationFrame: `${this.buildPlatform.globalVariablePrefix}.cancelAnimationFrame`,
      performance: `${this.buildPlatform.globalVariablePrefix}.performance`,
      navigator: `${this.buildPlatform.globalVariablePrefix}.navigator`,
      wx: this.buildPlatform.globalObject,
      miniProgramPlatform: `"${this.buildPlatform.globalObject}"`,
    };
    if (this.config.mode === 'development') {
      defineObject[
        'ngDevMode'
      ] = `${this.buildPlatform.globalObject}.__global.ngDevMode`;
    }
    this.config.plugins!.push(new DefinePlugin(defineObject));
  }
Example #2
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 #3
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,
  }
}
Example #4
Source File: webpack.config.ts    From tailchat with GNU General Public License v3.0 4 votes vote down vote up
plugins: Configuration['plugins'] = [
  new DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify(NODE_ENV),
    'process.env.SERVICE_URL': JSON.stringify(process.env.SERVICE_URL),
    'process.env.VERSION': JSON.stringify(
      `${process.env.VERSION || packageJson.version}-${dayjs().format(
        'YYYYMMDDHHmm'
      )}`
    ),
  }),
  new HtmlWebpackPlugin({
    title: 'Tailchat',
    inject: true,
    hash: false,
    favicon: path.resolve(ROOT_PATH, './assets/images/logo.svg'),
    template: path.resolve(ROOT_PATH, './assets/template.html'),
    preloadImage: `data:image/svg+xml;base64,${Buffer.from(
      fs.readFileSync(path.resolve(ROOT_PATH, './assets/images/ripple.svg'), {
        encoding: 'utf-8',
      })
    ).toString('base64')}`,
  }),
  new CopyPlugin({
    patterns: [
      {
        from: path.resolve(ROOT_PATH, '../locales'),
        to: 'locales',
      },
      {
        from: path.resolve(ROOT_PATH, './registry.json'),
        to: 'registry.json',
      },
      {
        from: path.resolve(ROOT_PATH, './assets/pwa.webmanifest'),
        to: 'pwa.webmanifest',
      },
      {
        from: path.resolve(ROOT_PATH, './assets/config.json'),
        to: 'config.json',
      },
      {
        from: path.resolve(ROOT_PATH, './assets/images/logo/'),
        to: 'images/logo/',
      },
      {
        from: path.resolve(ROOT_PATH, '../vercel.json'),
        to: 'vercel.json',
      },
    ],
  }) as any,
  new MiniCssExtractPlugin({ filename: 'styles-[contenthash].css' }),
  new WorkboxPlugin.GenerateSW({
    // https://developers.google.com/web/tools/workbox
    // these options encourage the ServiceWorkers to get in there fast
    // and not allow any straggling "old" SWs to hang around
    clientsClaim: true,
    skipWaiting: true,

    // Do not precache images
    exclude: [/\.(?:png|jpg|jpeg|svg)$/],

    maximumFileSizeToCacheInBytes: 8 * 1024 * 1024, // 限制最大缓存 8M

    // Define runtime caching rules.
    runtimeCaching: [
      {
        // Match any request that ends with .png, .jpg, .jpeg or .svg.
        urlPattern: /\.(?:png|jpg|jpeg|svg)$/,

        // Apply a cache-first strategy.
        // Reference: https://developers.google.com/web/tools/workbox/reference-docs/latest/module-workbox-strategies
        handler: 'CacheFirst',

        options: {
          // Use a custom cache name.
          cacheName: 'images',

          // Only cache 10 images.
          expiration: {
            maxEntries: 10,
            maxAgeSeconds: 14 * 24 * 60 * 60, // 2 week
          },
        },
      },
      //#region 插件缓存匹配
      {
        // 匹配内置 plugins 入口文件 以加速
        urlPattern: workboxPluginEntryPattern,
        handler: 'StaleWhileRevalidate',
        options: {
          cacheName: 'builtin-plugins-entry',
          expiration: {
            maxAgeSeconds: 24 * 60 * 60, // 1 day
          },
          cacheableResponse: {
            // 只缓存js, 防止404后台直接fallback到html
            headers: {
              'content-type': 'application/javascript; charset=utf-8',
            },
          },
        },
      },
      {
        // 匹配内置 plugins 内容 以加速
        urlPattern: workboxPluginDetailPattern,
        handler: 'StaleWhileRevalidate',
        options: {
          cacheName: 'builtin-plugins-detail',
          expiration: {
            maxAgeSeconds: 7 * 24 * 60 * 60, // 1 week
          },
          cacheableResponse: {
            // 只缓存js, 防止404后台直接fallback到html
            headers: {
              'content-type': 'application/javascript; charset=utf-8',
            },
          },
        },
      },
      //#endregion
    ],
  }),
  new WebpackBar({
    name: `Tailchat`,
  }),
]