使用parcel api 进行npm 项目

parcel 提供了api 我们可以方便的集成到项目中,直接进行代码的构建

参考需要构建的项目

  • index.html
<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
 
<body>
    <script type="module" src="app.js">
    </script>
    <my-element></my-element>
</body>
 
</html>

app.js

import {LitElement, html} from 'lit';
 
class MyElement extends LitElement {
  render() {
    return html`
      <div>Hello from MyElement!</div>
    `;
  }
}
customElements.define('my-element', MyElement);

package.json

{
  "name": "mynpm-app",
  "version": "1.0.0",
  "source": "index.html",
  "license": "MIT",
  "devDependencies": {
    "parcel": "^2.2.1"
  },
  "scripts": {
    "build": "parcel build",
    "watch": "parcel --public-url http://localhost:1234"
  },
  "dependencies": {
    "@parcel/config-default": "^2.2.1",
    "@parcel/core": "^2.2.1",
    "lit": "^2.1.2"
  }
}

api 构建

rong.js

const { Parcel } = require('@parcel/core');
let bundler = new Parcel({
    entries: 'index.html',
    defaultTargetOptions: { distDir: "mydemoapp/rong",publicUrl:"." },
    defaultConfig: '@parcel/config-default'
});
 
(async function () {
    try {
        let { bundleGraph, buildTime } = await bundler.run();
        let bundles = bundleGraph.getBundles();
        console.log(`✨ Built ${bundles.length} bundles in ${buildTime}ms!`);
    } catch (err) {
        console.log(err.diagnostics);
    }
})()

效果

 

 

 

 

说明

当然提供api 的构建工具是不少的,比如webpack,parcel 的好处很明显,简单,零配置(当然也是需要配置的,只是简单很多了)

参考资料

https://webpack.js.org/api/node/
https://parceljs.org/features/parcel-api/

posted on 2022-02-07 22:29  荣锋亮  阅读(115)  评论(0编辑  收藏  举报

导航