How to use parcel-bundler - 10 common examples

To help you get started, we’ve selected a few parcel-bundler examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github lin-xi / mark / script / dev.es.js View on Github external
import Parcel from 'parcel-bundler'
import path from 'path'
import electron from 'electron'


const option = {
  watch: true,
  // target: 'electron',
  publicUrl: './',
  cache: true,
  hmr: false
}

let index = new Parcel(path.join(__dirname, '../src/index.html'), option)
index.bundle().then(() => {
  console.log('>> done')
  var proc = require('child_process')

  var child = proc.spawn(electron, ['.', '--debug'], {
    stdio: 'inherit'
  })
  child.on('close', function (code) {
    process.exit(code)
  })
})
github ifiokjr / remirror / @remirror / cli / src / commands / bundle / cli-parcel.ts View on Github external
const tempDir = path.join(os.tmpdir(), uniqueId());
  const tempFileName = 'remirror-webview.js';
  const tempFilePath = path.join(tempDir, tempFileName);
  const outDir = workingDirectory;
  const isTs = bool(source.match(/\.tsx?$/));
  const outFilePath = path.join(outDir, isTs ? 'file.ts' : 'file.js');
  // Parcel config
  const options: ParcelOptions = {
    outDir: tempDir,
    outFile: tempFileName,
    sourceMaps: false,
    minify: true,
    watch: false,
    logLevel: 1,
  };
  const parcel = new Bundler(entryFile, options);
  async function build(bundler: Bundler) {
    try {
      // create the bundle
      await bundler.bundle();

      // Read the bundle and insert it into script template
      const script = await readFile(tempFilePath, 'utf-8');
      const finalOutput = isTs ? createTSFile(script) : createJSFile(script);
      await writeFile(outFilePath, finalOutput, 'utf-8');

      // Remove junk
      await clearPath(`${tempDir}/*`);
    } catch (error) {
      console.error(error);
    }
  }
github lin-xi / mark / script / pack.es.js View on Github external
import Parcel from 'parcel-bundler'
import path from 'path'
import fs from 'fs-extra'
const builder = require('electron-builder')

const option = {
  watch: false,
  cache: false,
  // target: 'electron',
  publicUrl: './',
  hmr: false
}

let index = new Parcel(path.join(__dirname, '../src/index.html'), option)
index.bundle().then(() => {
  fs.copySync(path.join(__dirname, '../logo.png'), path.join(__dirname, '../dist/logo.png'))
  fs.copySync(path.join(__dirname, '../logo.svg'), path.join(__dirname, '../dist/logo.svg'))
  fs.copySync(path.join(__dirname, '../src/index.js'), path.join(__dirname, '../dist/index.js'))
  fs.copySync(path.join(__dirname, '../src/auto-updater.js'), path.join(__dirname, '../dist/auto-updater.js'))
  fs.copySync(path.join(__dirname, '../src/services'), path.join(__dirname, '../dist/services'))
  fs.copySync(path.join(__dirname, '../package.json'), path.join(__dirname, '../dist/package.json'))

  console.log('>> done')
  console.log('>> start pack...')

  builder.build({
    config: {
      'appId': 'com.mark.app',
      'productName': 'Mark',
      'directories': {
github remoteinterview / zero / packages / parcel-bundler / index.js View on Github external
require("./applyMods")(); // apply our mods
// this is a wrapper around parcel, need to apply patches to parcel
var Bundler = require("parcel-bundler");
var localRequire = require("parcel-bundler/src/utils/localRequire");
const logger = require("@parcel/logger");
const pkg = require("./package");
const path = require("path");

// limit workers parcel can spawn to 0 by default
// we do this because we spawn a parcel process for each page
// and we don't want each of them to spawn their own 2 or so worker processes.
process.env.PARCEL_WORKERS = process.env.PARCEL_WORKERS || 0;

/// modify parcel to load plugins from zero's folder instead of user's package.json
Bundler.prototype.loadPlugins = async function() {
  let relative = path.dirname(
    path.join(require.resolve("parcel-bundler"), "..")
  );
  if (!pkg) {
    return;
  }

  try {
    let deps = Object.assign({}, pkg.dependencies, pkg.devDependencies);
    for (let dep in deps) {
      const pattern = /^(@.*\/)?parcel-plugin-.+/;
      if (pattern.test(dep)) {
        let plugin = await localRequire(dep, relative);
        await plugin(this);
      }
    }
github kevincharm / parcel-plugin-web-extension / src / WebExtensionPackager.js View on Github external
async resolveAssetContents(asset) {
        let contents = asset.generated[this.bundle.type]
        if (!contents || (contents && contents.path)) {
            contents = await fs.readFile(contents ? contents.path : asset.name)
        }

        console.log(asset.generated)

        // Create sub-directories if needed
        if (this.bundle.name.includes(path.sep)) {
            await fs.mkdirp(path.dirname(this.bundle.name))
        }

        // Add the hot-reload.js script to background scripts
        const json = JSON.parse(contents)
        json.background = json.background || {}
        json.background.scripts = json.background.scripts || []
        json.background.scripts.unshift('hot-reload.js')
        contents = JSON.stringify(json)

        return contents
    }
github kevincharm / parcel-plugin-web-extension / src / WebExtensionPackager.js View on Github external
async resolveAssetContents(asset) {
        let contents = asset.generated[this.bundle.type]
        if (!contents || (contents && contents.path)) {
            contents = await fs.readFile(contents ? contents.path : asset.name)
        }

        console.log(asset.generated)

        // Create sub-directories if needed
        if (this.bundle.name.includes(path.sep)) {
            await fs.mkdirp(path.dirname(this.bundle.name))
        }

        // Add the hot-reload.js script to background scripts
        const json = JSON.parse(contents)
        json.background = json.background || {}
        json.background.scripts = json.background.scripts || []
        json.background.scripts.unshift('hot-reload.js')
        contents = JSON.stringify(json)
github threadheap / serverless-plugin-parcel / src / index.ts View on Github external
watch: this.options.watch || false
        };
        const config = {
            ...defaults,
            ...options
        };

        if (this.options.watch) {
            this.isWatching = true;
        }

        if (this.entries.length === 1) {
            // watch single function
            const entry = this.entries[0];

            const bundler = new Bundler(entry, {
                ...config,
                outDir: path.relative(
                    this.originalServicePath,
                    path.join(this.buildPath, path.dirname(entry))
                )
            });

            this.invokeBundle = await bundler.bundle();

            if (this.isWatching) {
                (bundler as any).on('buildEnd', () => {
                    this.sls.pluginManager.spawn('invoke:local');
                });
            }
        } else {
            for (const entry of this.entries) {
github smapiot / piral / src / packages / piral-cli / src / apps / build-piral.ts View on Github external
} = options;
  const entryFiles = await retrievePiralRoot(baseDir, entry);
  const targetDir = dirname(entryFiles);
  const { name, version, root, dependencies, ...pilets } = await retrievePiletsInfo(entryFiles);
  const { externals } = pilets;
  const dest = getDestination(entryFiles, resolve(baseDir, target));

  await checkCliCompatibility(root);

  if (fresh) {
    await clearCache(root, cacheDir);
  }

  await removeDirectory(dest.outDir);

  modifyBundlerForPiral(Bundler.prototype, targetDir);

  // everything except release -> build develop
  if (type !== 'release') {
    logInfo('Starting build ...');

    // we'll need this info for later
    const originalPackageJson = resolve(root, 'package.json');
    const { files: originalFiles = [] } = require(originalPackageJson);
    const appDir = 'app';
    const outDir = await bundleFiles(name, true, targetDir, externals, entryFiles, dest, join('develop', appDir), {
      cacheDir,
      watch: false,
      sourceMaps,
      contentHash,
      minify,
      scopeHoist,
github kevincharm / parcel-plugin-web-extension / src / WebExtensionPackager.js View on Github external
async addAsset(asset) {
        const artifactsDir = path.resolve(
            asset.options.outDir,
            '..',
            'artifacts'
        )
        await fs.mkdirp(artifactsDir)

        // Write the manifest.json
        const bundlePath = path.parse(this.bundle.name)
        const contents = await this.resolveAssetContents(asset)
        const hotReloadScriptFilename = path.resolve(
            bundlePath.dir,
            'hot-reload.js'
        )
        await fs.writeFile(hotReloadScriptFilename, hotReloadScript, {
            encoding: 'utf8'
        })
        const manifestJsonFilename = path.resolve(
            bundlePath.dir,
            bundlePath.name + '.json'
        )
        await fs.writeFile(manifestJsonFilename, contents, { encoding: 'utf8' })
github kevincharm / parcel-plugin-web-extension / src / WebExtensionPackager.js View on Github external
// Write the manifest.json
        const bundlePath = path.parse(this.bundle.name)
        const contents = await this.resolveAssetContents(asset)
        const hotReloadScriptFilename = path.resolve(
            bundlePath.dir,
            'hot-reload.js'
        )
        await fs.writeFile(hotReloadScriptFilename, hotReloadScript, {
            encoding: 'utf8'
        })
        const manifestJsonFilename = path.resolve(
            bundlePath.dir,
            bundlePath.name + '.json'
        )
        await fs.writeFile(manifestJsonFilename, contents, { encoding: 'utf8' })

        // Package the extension (XPI/CRX)
        const zipped = await zipDir(this.options.outDir)
        const zippedFilename = path.resolve(
            artifactsDir,
            bundlePath.name + '.zip'
        )
        this.size = zipped.length
        await fs.writeFile(zippedFilename, zipped)
    }