webpack#Configuration TypeScript Examples

The following examples show how to use webpack#Configuration. 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: utils.ts    From tailchat with GNU General Public License v3.0 7 votes vote down vote up
export function configureLoader(config: DefaultWebpackConfig & Configuration) {
  config.resolveLoader.alias = {
    'source-ref-loader': loaderPath,
  };

  config.module.rules.push({
    test: /\.tsx$/,
    loader: 'source-ref-loader',
    options: {
      available: true,
    },
  });
}
Example #2
Source File: plugin.test.ts    From react-docgen-typescript-plugin with MIT License 6 votes vote down vote up
function compile(config: Configuration): Promise<string> {
  return new Promise((resolve, reject) => {
    const compiler = webpack(config);

    // eslint-disable-next-line
    // @ts-ignore: There's a type mismatch but this should work based on webpack source
    compiler.outputFileSystem = ensureWebpackMemoryFs(
      createFsFromVolume(new Volume())
    );
    const memfs = compiler.outputFileSystem;

    compiler.run((error, stats) => {
      if (error) {
        return reject(error);
      }

      if (stats?.hasErrors()) {
        return reject(stats.toString("errors-only"));
      }

      memfs.readFile(
        "./dist/main.js",
        {
          encoding: "utf-8",
        },
        // eslint-disable-next-line
        // @ts-ignore: Type mismatch again
        (err, data) => (err ? reject(err) : resolve(data))
      );

      return undefined;
    });
  });
}
Example #3
Source File: webpack.config.ts    From format-imports-vscode with MIT License 6 votes vote down vote up
config: Configuration = {
  mode: 'development',
  target: 'node',
  entry: './src/extension.ts',
  output: {
    path: path.resolve(__dirname, 'out'),
    filename: 'extension.js',
    libraryTarget: 'commonjs2',
  },
  externals: {
    vscode: 'commonjs vscode',
  },
  resolve: {
    mainFields: ['browser', 'module', 'main'],
    extensions: ['.ts', '.js'],
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        exclude: /node_modules/,
        use: 'ts-loader',
      },
    ],
  },
}
Example #4
Source File: index.ts    From reskript with MIT License 6 votes vote down vote up
runBuild = (configuration: Configuration[]): Promise<Stats> => {
    const executor = (resolve: (value: Stats) => void) => webpack(
        configuration as Configuration, // https://github.com/Microsoft/TypeScript/issues/14107
        (err?: Error, stats?: Stats) => {
            if (err) {
                logger.error(err.toString());
                process.exit(22);
            }

            if (!stats) {
                logger.error('Unknown error: webpack does not return its build stats');
                process.exit(22);
            }

            const toJsonOptions = {all: false, errors: true, warnings: true, assets: true};
            // webpack的`toJson`的定义是错的
            const {errors, warnings} = stats.toJson(toJsonOptions);
            for (const error of reject(isNil, errors ?? [])) {
                printWebpackResult('error', error as unknown as WebpackResult);
            }
            for (const warning of reject(isNil, warnings ?? [])) {
                printWebpackResult('warn', warning as unknown as WebpackResult);
            }

            if (stats.hasErrors()) {
                process.exit(22);
            }

            resolve(stats);
        }
    );

    return new Promise(executor);
}
Example #5
Source File: webpack.config.ts    From serverless-SAM-typescript-boilerplate with Apache License 2.0 6 votes vote down vote up
config: Configuration = {
  entry: {
    defaultApiResponses: resolve(__dirname, 'src', 'defaultResponses.ts'),
  },
  target: 'node',
  mode: conf.prodMode ? 'production' : 'development',
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
      },
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
  output: {
    path: resolve(__dirname, 'dist'),
    filename: '[name].js',
    libraryTarget: 'commonjs2',
  },
  devtool: 'source-map',
  plugins: [],
}
Example #6
Source File: plugin.test.ts    From react-docgen-typescript-plugin with MIT License 6 votes vote down vote up
getConfig = (
  options = {},
  config: { title?: string } = {}
): Configuration => ({
  mode: "none",
  entry: { main: "./src/__tests__/__fixtures__/Simple.tsx" },
  plugins: [new ReactDocgenTypeScriptPlugin(options)],
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        loader: "ts-loader",
        options: {
          transpileOnly: true,
        },
      },
    ],
  },
  ...config,
})
Example #7
Source File: webpack.config.ts    From tailchat with GNU General Public License v3.0 6 votes vote down vote up
splitChunks: Required<Configuration>['optimization']['splitChunks'] = {
  chunks: 'async',
  minSize: 20000,
  minRemainingSize: 0,
  minChunks: 1,
  maxAsyncRequests: 30,
  maxInitialRequests: 30,
  enforceSizeThreshold: 50000,
  cacheGroups: {
    vendors: {
      chunks: 'initial',
      name: 'vendors',
      test: /[\\/]node_modules[\\/]/,
      priority: -10,
      reuseExistingChunk: true,
      maxSize: 2 * 1000 * 1000,
    },
    default: {
      minChunks: 2,
      priority: -20,
      reuseExistingChunk: true,
    },
  },
}
Example #8
Source File: addWebpackConfig.ts    From nextclade with MIT License 6 votes vote down vote up
export function addWebpackConfig(nextConfig: NextConfig, customWebpackConfig: CustomWebpackConfig) {
  const webpack = (webpackConfig: Configuration, options: WebpackConfigContext) => {
    const newConfig = customWebpackConfig(nextConfig, webpackConfig, options)

    if (typeof nextConfig.webpack === 'function') {
      return nextConfig.webpack(newConfig, options)
    }

    return newConfig
  }

  return { ...nextConfig, webpack }
}
Example #9
Source File: webpack.ts    From vanilla-extract with MIT License 6 votes vote down vote up
defaultWebpackConfig: Configuration = {
  resolve: {
    extensions: ['.js', '.json', '.ts', '.tsx'],
  },
  devtool: 'source-map',
  optimization: {
    minimize: false,
  },
  plugins: [
    new HtmlWebpackPlugin(),
    new MiniCssExtractPlugin({
      filename: stylesheetName,
    }),
  ],
}
Example #10
Source File: webpack.config.prod.ts    From flect-chime-sdk-demo with Apache License 2.0 6 votes vote down vote up
renderer: Configuration = {
    ...base,
    // target: 'electron-renderer',
    target: 'web',
    entry: {
        index: './src/web/index.tsx',
    },
    plugins: [
        new MiniCssExtractPlugin(),
        new HtmlWebpackPlugin({
            template: './src/web/index.html',
            minify: true,
            inject: 'body',
            filename: 'index.html',
            scriptLoading: 'blocking',
        }),
    ],
}
Example #11
Source File: webpack.ts    From mpflow with MIT License 6 votes vote down vote up
export function getCompiler(config: Configuration): Compiler {
  const fullConfig = merge(
    {
      mode: 'development',
      devtool: false,
      target: 'node',
      optimization: {
        minimize: false,
        namedModules: false,
      },
      output: {
        filename: '[name].bundle.js',
        chunkFilename: '[name].chunk.js',
        libraryTarget: 'commonjs2',
        pathinfo: false,
      },
    },
    config,
  )

  const compiler = webpack(fullConfig)

  const outputFileSystem = createFsFromVolume(new Volume())

  compiler.outputFileSystem = Object.assign(outputFileSystem, { join: path.join.bind(path) })

  return compiler
}
Example #12
Source File: webpack.script.babel.ts    From WELearnHelper with GNU General Public License v3.0 6 votes vote down vote up
config: Configuration = {
    mode: "production",
    optimization: {
        minimize: false,
    },
    plugins: [
        new webpack.EnvironmentPlugin({
            CRX: false,
            LITE: false,
        }),
        new webpack.BannerPlugin({
            banner: fs.readFileSync("./headers.js", "utf8"),
            raw: true,
            entryOnly: true,
        }),
    ],
    externals: {
        vue: "Vue",
        $: "jQuery",
    },
}
Example #13
Source File: webpack.main.config.ts    From angular-electron-admin with Apache License 2.0 6 votes vote down vote up
mainConfig: Configuration = {
  mode: process.env.NODE_ENV as MODE_TYPE,
  target: 'electron-main',
  devtool: 'source-map',
  entry: {
    main: resolve(__dirname, '../../src/main/main.ts')
  },
  output: {
    filename: '[name].js',
    path: resolve(__dirname, '../../dist/main'),
    libraryTarget: 'commonjs',
  },
  externals: [...dependencies],
  node: {
    __dirname: process.env.NODE_ENV !== 'production',
    __filename: process.env.NODE_ENV !== 'production'
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: [
          {
            loader: 'ts-loader',
            options: {
              configFile: resolve(__dirname, '../../src/tsconfig.main.json'),
            },
          },
        ],
        exclude: /node_modules/,
      },
    ]
  },
  plugins: [],
  resolve: {
    extensions: ['.ts', '.json', '.js']
  },
}
Example #14
Source File: webpack.common.babel.ts    From TsingHuaELTHelper with GNU General Public License v3.0 6 votes vote down vote up
config: Configuration = {
    entry: "./src/main.ts",
    output: {
        //__dirname即当前文件所在目录的路径,此处是根目录
        path: path.resolve(__dirname, "./dist"),
        filename: `TsingHuaELTHelper${PACKAGE_JSON.version}.user.js`,
    },
    module: {
        rules: rules,
    },
    plugins: [
        // 使用webpack打包vue文件,必须需要这个插件
        new VueLoaderPlugin(),
        new CleanWebpackPlugin({ cleanStaleWebpackAssets: false }),
        new HtmlWebpackPlugin({
            title: "Output Management",
        }),
        new webpack.optimize.LimitChunkCountPlugin({
            maxChunks: 1,
        }),
    ],
    resolve: {
        //import的时候,可以不用写扩展名
        extensions: [".ts", ".js", ".vue", ".json"],
        alias: {
            "@src": path.resolve(__dirname, "./src/"),
            "@utils": path.resolve(__dirname, "./src/utils/"),
            "@assets": path.resolve(__dirname, "./assets/"),
            "@plugins": path.resolve(__dirname, "./src/plugins/"),
        },
    },
}
Example #15
Source File: webpack.config.ts    From serverless-SAM-typescript-boilerplate with Apache License 2.0 6 votes vote down vote up
webpackConfig: Configuration = {
  entry: entries,
  target: 'node',
  mode: conf.prodMode ? 'production' : 'development',
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
      },
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
    alias: tsPaths,
  },
  output: {
    path: resolve(__dirname, 'dist'),
    filename: '[name].js',
    libraryTarget: 'commonjs2',
  },
  devtool: 'source-map',
  plugins: [],
}
Example #16
Source File: webpack.common.babel.ts    From WELearnHelper with GNU General Public License v3.0 6 votes vote down vote up
config: Configuration = {
    entry: "./src/main.ts",
    output: {
        //__dirname即当前文件所在目录的路径,此处是根目录
        path: path.resolve(__dirname, "./dist"),
        filename: `WELearnHelper${PACKAGE_JSON.version}.user.js`,
    },
    module: {
        rules: rules,
    },
    plugins: [
        // 使用webpack打包vue文件,必须需要这个插件
        new VueLoaderPlugin(),
        new CleanWebpackPlugin({ cleanStaleWebpackAssets: false }),
        new HtmlWebpackPlugin({
            title: "Output Management",
        }),
        new webpack.optimize.LimitChunkCountPlugin({
            maxChunks: 1,
        }),
    ],
    resolve: {
        //import的时候,可以不用写扩展名
        extensions: [".ts", ".js", ".vue", ".json"],
        alias: {
            "@src": path.resolve(__dirname, "./src/"),
            "@utils": path.resolve(__dirname, "./src/utils/"),
            "@assets": path.resolve(__dirname, "./assets/"),
            "@plugins": path.resolve(__dirname, "./src/plugins/"),
        },
    },
}
Example #17
Source File: webpack.config.base.ts    From vscode-sound-player with MIT License 6 votes vote down vote up
config = {
    target: 'node',
    entry: {
        extension: resolve(__dirname, '../src/extension.ts')
    },
    module: {
        rules: [
            {
                test: /\.ts$/,
                exclude: /node_modules/,
                use: [{
                    loader: 'ts-loader',
                    options: {
                        compilerOptions: {
                            module: 'es6'
                        },
                        transpileOnly: true,
                    },
                }],
            }
        ]
    },
    externals: {
        vscode: 'commonjs vscode'
    },
    resolve: {
        extensions: ['.ts', '.js']
    },
    output: {
        filename: '[name].js',
        path: resolve(__dirname, '../dist'),
        libraryTarget: 'commonjs2',
        devtoolModuleFilenameTemplate: '../[resource-path]'
    }
} as Configuration
Example #18
Source File: webpack.config.prod.ts    From flect-chime-sdk-demo with Apache License 2.0 5 votes vote down vote up
base: Configuration = {
    mode: 'production',
    node: {
        __dirname: false,
        __filename: false,
    },
    resolve: {
        extensions: ['.js', '.ts', '.jsx', '.tsx', '.json'],
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        publicPath: './',
        filename: '[name].js',
        assetModuleFilename: 'images/[name][ext]',
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                exclude: /node_modules/,
                // include: [
                //   /src/,
                //   /node_modules\/@ffmpeg\/core/
                // ],
                use: [
                    { loader: 'ts-loader' },
                    { loader: 'ifdef-loader', options: { DEBUG: false } },
                ],
            },
            {
                test: /\.s?css$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    {
                        loader: 'css-loader',
                        options: {
                            sourceMap: false,
                            importLoaders: 1,
                        },
                    },
                    {
                        loader: 'sass-loader',
                        options: {
                            sourceMap: false,
                        },
                    },
                ],
            },
            {
                test: /\.(bmp|ico|gif|jpe?g|png|svg|ttf|eot|woff?2?)$/,
                type: 'asset/resource',
            },
        ],
    },
    stats: 'errors-only',
    performance: { hints: false },
    optimization: { minimize: true },
    devtool: undefined,
}
Example #19
Source File: webpack.config.prod.ts    From nebula-dashboard with Apache License 2.0 5 votes vote down vote up
publicConfig: Configuration = {
  // devtool: 'cheap-module-source-map',
  entry: path.join(__dirname, `../src/index.tsx`),
  mode: 'production',
  output: {
    path: path.join(__dirname, '../public'),
    filename: '[name].[chunkhash].js',
    chunkFilename: '[name].[contenthash].js',
    publicPath:  '/',
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader'],
      },
    ],
  },
  optimization: {
    minimizer: [
      new TerserPlugin(),
    ],
    runtimeChunk: {
      name: 'manifest',
    },
    splitChunks: {
      cacheGroups: {
        vendors: {
          name: 'vendors',
          test: /node_modules/,
          chunks: 'all',
        },
      },
    },
  },

  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production'),
      },
    }),

    new CleanWebpackPlugin(),

    new MiniCssExtractPlugin({
      filename: '[name].[hash].css',
      chunkFilename: '[id].[hash].css',
    }),

    // new ManifestPlugin({
    //   fileName: path.resolve(__dirname, '../config/manifest.json'),
    //   publicPath: '',
    // }),
  ],
}
Example #20
Source File: webpack.crx.babel.ts    From TsingHuaELTHelper with GNU General Public License v3.0 5 votes vote down vote up
config: Configuration = {
    entry: {
        main: "./src/main.ts",
        inject: "./src/inject.ts",
        content: "./src/content.ts",
        background: "./src/background.ts",
    },
    output: {
        path: path.resolve(__dirname, "./dist"),
        filename: `[name].js`,
    },
    module: {
        rules: rules,
    },
    plugins: [
        // 使用webpack打包vue文件,必须需要这个插件
        new VueLoaderPlugin(),
        new CleanWebpackPlugin({ cleanStaleWebpackAssets: false }),
        new webpack.optimize.LimitChunkCountPlugin({
            maxChunks: 1,
        }),
        new CopyPlugin({
            patterns: [
                { from: "manifest.json", to: "" },
                { from: "assets/icon.png", to: "" },
            ],
        }),
        new webpack.EnvironmentPlugin({
            CRX: true,
            LITE: false,
        }),
    ],
    resolve: {
        //import的时候,可以不用写扩展名
        extensions: [".ts", ".js", ".vue", ".json"],
        alias: {
            "@src": path.resolve(__dirname, "./src/"),
            "@utils": path.resolve(__dirname, "./src/utils/"),
            "@assets": path.resolve(__dirname, "./assets/"),
            "@plugins": path.resolve(__dirname, "./src/plugins/"),
        },
    },
}
Example #21
Source File: webpack.config.prod.ts    From flect-chime-sdk-demo with Apache License 2.0 5 votes vote down vote up
main: Configuration = {
    ...base,
    target: 'electron-main',
    entry: {
        main: './src/main.ts',
    },
}
Example #22
Source File: rebuild.ts    From codedoc with MIT License 5 votes vote down vote up
export function rebuild(
  files: SimpleLine<File<undefined>>,
  config: CodedocConfig,
  builder: ContentBuilder,
  assets: BuildAssets,
  webpackConfig?: Configuration,
): Promise<BuildAssets> {
  const _ogstyles = assets.styles.theme.registry.toString();

  return new Promise((resolve, reject) => {
    files
    .peek(file => console.log(`${chalk.gray('# rebuilding ........ ' + join(file.root, file.path)) }`))
    .pipe(
      readFile(),
      content(builder, assets.toc, config, assets.styles),
      post(assets.bundle.collect()),
      post(namespace(config)),
      post(pageSpecificMeta),
      (file: File<Compiled>) => {
        (config.page.post || []).forEach(p => file.content.post(html => p(html, file, config)));
        return file;
      },
      mapExt<Compiled>(() => '.html'),
      mapRoot(() => config.dest.html),
      save(),
    )
    .pipe(
      handleError((err, file, rethrow) => {
        rethrow(new Error(chalk`{redBright # ERROR} in {underline ${file.path}}\n${err?.message || err}`));
      }) as any as Function<File<any>, File<any>>,
    )
    .peek(file => console.log(`${chalk.green('#')}${chalk.gray(' rebuilt:: .........')} ${join(file.root, file.path)}`))
    .process()
    .collect(sequentially, async (built) => {
      if (assets.styles.theme.registry.toString() !== _ogstyles) {
        console.log(`${chalk.gray('# rebuilding ........ ' + assets.styles.path)}`);
        await assets.styles.save();
        console.log(`${chalk.green('#')} ${chalk.gray('rebuilt:: .........')} ${assets.styles.path}`)
      }

      if (assets.bundle.repack) {
        console.log(`${chalk.gray('# rebuilding ........ ' + assets.bundle.path)}`);
        await save(assets.bundle, webpackConfig);
        assets.bundle.repack = false;
        console.log(`${chalk.green('#')} ${chalk.gray('rebuilt:: .........')} ${assets.bundle.path}`);
      }

      if (config.afterBuild) {
        console.log(chalk.gray('# running after build hooks ...'));
        for (let hook of config.afterBuild) {
          console.log(chalk.gray('# running ......... ' + hook.name + '()'));
          await hook({ config, built, source: files, partial: true });
          console.log(`${chalk.green('#')} ${chalk.gray('finished:: ......')} ${hook.name}()`);
        }
      }

      resolve(assets);
    }, reject);
  });
}
Example #23
Source File: ServiceRunner.ts    From mpflow with MIT License 5 votes vote down vote up
/**
   * 获取所有的 webpack 配置
   */
  async resolveWebpackConfigs(): Promise<Record<string, Configuration>> {
    return this.service.resolveWebpackConfigs()
  }
Example #24
Source File: webpack.config.ts    From flect-chime-sdk-demo with Apache License 2.0 5 votes vote down vote up
config: Configuration = {
  mode: 'development',
  target: 'web',
  node: {
    __dirname: false,
    __filename: false,
  },
  resolve: {
    extensions: ['.js', '.ts', '.jsx', '.tsx', '.json'],
  },
  entry: {
    app: './src/web/index.tsx',
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    publicPath: './',
    filename: '[name].js',
    assetModuleFilename: 'images/[name][ext]',
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        exclude: /(node_modules|tests|mocks)/,
        use: 'ts-loader',
      },
      {
        test: /\.s?css$/,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: 'css-loader',
            options: {
              sourceMap: true,
              importLoaders: 1,
            },
          },
          {
            loader: 'sass-loader',
            options: {
              sourceMap: true,
            },
          },
        ],
      },
      {
        test: /\.(bmp|ico|gif|jpe?g|png|svg|ttf|eot|woff?2?)$/,
        type: 'asset/resource',
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin(),
    new HtmlWebpackPlugin({
      template: './src/web/index.html',
      filename: 'index.html',
      scriptLoading: 'blocking',
      inject: 'body',
      minify: false,
    }),
  ],
  stats: 'errors-only',
  performance: { hints: false },
  optimization: { minimize: false },
  devtool: 'cheap-module-source-map'
}
Example #25
Source File: webpack.config.ts    From mops-vida-pm-watchdog with MIT License 5 votes vote down vote up
configuration: Configuration = {
  context: __dirname,
  devtool: 'source-map',
  optimization: { splitChunks: { chunks: 'all' } },
  resolve: { extensions: ['.ts', '.tsx', '.js', '.json'] },
  module: {
    rules: [
      {
        test: /.tsx?$/,
        loader: require.resolve('ts-loader'),
      },
      {
        test: /\.css$/,
        use: [
          CSSPlugin.loader,
          {
            loader: require.resolve('css-loader'),
            options: { sourceMap: true },
          },
        ],
      },
      {
        test: /\.scss$/,
        use: [
          CSSPlugin.loader,
          {
            loader: require.resolve('css-loader'),
            options: {
              sourceMap: true,
              importLoaders: 2,
              modules: true,
              esModule: true,
            },
          },
          {
            loader: TypedCSSLoader,
            options: { mode: 'local' },
          },
          require.resolve('sassjs-loader'),
        ],
      },
    ],
  },
  devServer: { hot: false, inline: false, https: true },
  plugins: [
    new HTMLPlugin({
      title: 'MOPS·VIDA PM Watchdog',
      favicon: require.resolve('./assets/air-pollution-icon.png'),
    }),
    new CSSPlugin({ filename: '[name].css' }),
    new HTMLPartialPlugin({
      path: require.resolve('./assets/partials/analytics.html'),
      location: 'head',
      options: { id: 'UA-168944052-1' },
    }),
  ],
}
Example #26
Source File: ServiceRunner.ts    From mpflow with MIT License 5 votes vote down vote up
/**
   * 获取所有的 webpack 配置
   */
  async resolveWebpackConfigs(): Promise<Record<string, Configuration>> {
    const webpackConfigs: Map<string, ((config: WebpackChain, id: string) => void)[]> = new Map()
    const { configureWebpack, configureWebpackChain } = this.config
    const configs: Record<string, Configuration> = {}

    /**
     * 设置对应的 webpack 配置
     * @param config
     */
    function configure(config: (config: WebpackChain, id: string) => void): void
    function configure(id: string, config: (config: WebpackChain, id: string) => void): void
    function configure(id: any, config?: any): void {
      if (!config) {
        config = id
        id = undefined
      }
      if (id !== undefined) {
        const webpackConfig = webpackConfigs.get(id)
        if (!webpackConfig) throw new Error(`找不到对应的 webpack 配置 id=${id}`)
        webpackConfig.push(config)
      } else {
        webpackConfigs.forEach(webpackConfig => webpackConfig.push(config))
      }
    }

    /**
     * 添加一个 webpack 构建配置
     * @param id
     * @param config
     */
    function addConfig(id: string, config: (config: WebpackChain, id: string) => void): boolean {
      if (webpackConfigs.has(id)) return false

      webpackConfigs.set(id, [config])
      return true
    }

    /**
     * 判断是否存在 webpack 配置
     */
    function hasConfig(id: string): boolean {
      return webpackConfigs.has(id)
    }

    for (const handler of this.configWebpackHandlers) {
      await handler(
        {
          configure,
          addConfig,
          hasConfig,
        },
        this.mode,
      )
    }

    webpackConfigs.forEach((configurationHandlers, id) => {
      const config = new WebpackChain()

      configurationHandlers.forEach(handler => handler(config, id))

      if (configureWebpackChain) configureWebpackChain(config)

      const chainConfig = config.toConfig()
      const resultConfig =
        typeof configureWebpack === 'function'
          ? configureWebpack(chainConfig)
          : merge(chainConfig, configureWebpack || {})

      configs[id] = resultConfig
    })

    return configs
  }
Example #27
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 #28
Source File: webpack.config.dev.ts    From vscode-sound-player with MIT License 5 votes vote down vote up
config = {
    mode: 'development',
    devtool: 'cheap-module-source-map',
} as Configuration
Example #29
Source File: development.ts    From reskript with MIT License 5 votes vote down vote up
factory: ConfigurationFactory = () => {
    const config: Configuration = {
        devtool: 'eval-cheap-module-source-map',
    };

    return config;
}