安装parcel
npm install parcel-bundler -S
传统的前端网页parcel的打包方式示例
文件目录构建
//server.js,用于搭建本地服务器,通过koa-static
const Koa = require('koa')
const {resolve} = require('path')
// koa-static 本地静态资源服务器
const serve = require('koa-static')
const app = new Koa()
app.use(serve(resolve(__dirname,'./')))
app.listen(2256)
//index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>parcel 演示</title>
<link rel="stylesheet" href="https://cdn.bootcss.com/twitter-bootstrap/4.3.0/css/bootstrap.min.css">
<link rel="stylesheet" href="./css/index.css">
</head>
<body>
<div id="app">Parcel 打包案例</div>
<script src="https://cdn.bootcss.com/jquery/3.3.0/jquery.min.js"></script>
<script src="./js/index.js"></script>
</body>
</html>
配置parcel,在package.json中
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server/index.js",
"build":"parcel build parcel/index.html --no-cache -d parcel/distcm --public-url /dist/"
},
打包构建哪一个目录文件parcel build parcel/index.html
,指定打包后的文件目录 -d parcel/distcm
,--public-url /dist/
指定index.html中引入的样式文件和监本文件指定打包后相对的文件位置
运行命令行,用parcel进行打包文件输出
npm run build
打包成功,生成目录dist
测试打包后的代码是否可以运行
node parcel/server.js
单页应用react,parcel打包输出
因为在react中会使用到大量的新的语法特性,那么虽然parcel本身基本上是零配置,但是对于新语法特性的输出,是需要配置的
在项目的根目录下,与package.json
同级的目录,新建一个文件.babelrc
{
"presets":["env","stage-0","react"],
"plugins":[
"transform-runtime",
"transform-decoratorslegacy",
"transform-class-properties"
]
}
安装配置的babel插件
npm i babel-preset-env -S
npm i babel-preset-stage-0 -S
npm i babel-preset-react -S
npm i babel-plugins-transform-runtime -S
npm install --save-dev babel-plugin-transform-decorators-legacy
npm install --save-dev babel-plugin-transform-class-properties
此时在运行打包命令之前需要修改一下package.json
文件中的命令,添加rm -rf parcel/distcm
作用是每次打包之前删除parcel文件夹下的distcm目录
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server/index.js",
"build": "rm -rf parcel/distcm && parcel build parcel/index.html --no-cache -d parcel/distcm --public-url /distcm/"
}
因为单独引入了react
,react-dom
,所以进行安装
npm i react react-dom -S
开始打包npm run build
打包后的文件
启动服务,测试打包后的文件是否可以运行,访问的时候路径需要更改为当前打包后的文件的路径,distcm/index.html
http://localhost:2256/distcm/index.html