如何在CRA项目中用parcel替换webpack?

nin*_*alt 9 webpack create-react-app parceljs

我有一个CRA项目设置,它工作正常.但是我正在考虑将它弹出并用Parcel.js替换Webpack.弹射后,我该怎么办?是index.js该文件src的文件夹,我需要对地块的唯一文件?

Tha*_*Luz 19

如果不弹出(删除的文件较少),您的生活将会更轻松.您也不需要webpack,Parcel将成为您的捆绑包.

如果您的设置仍然接近CRA为您提供的开箱即用,那么您需要做的就是:

  1. 卸载react-scripts: $ npm rm react-scripts

  2. 安装parcel-bundler: $ npm i -D parcel-bundler

  3. CRA和Parcel之间的一个主要区别在于,在CRA中,您的条目始终是您的src/index.js,public/index.html更像是模板.在Parcel中,您可以将任何.js文件作为条目,也可以使用任何.html文件,这很棒.因此,将所有文件移动publicsrc目录,然后您可以继续删除public文件夹,因为现在所有文件都是源文件.由于您的新条目是index.html让我们正确指向文件.

  4. 删除模板变量%PUBLIC_URL%在你index.html和点直接将文件.让我们说如果你放置index.html并且file.ext两者都在你的src文件夹的根目录,href="%PUBLIC_URL%/file.ext"应该成为href="./file.ext".

  5. CRA会<script />自动在html的末尾注入一个标签,但是在Parcel中你需要指定它以便知道要捆绑什么.因此<script src="./index.js" />,在您之前添加到您的身体标记文件的底部</body>(如果您将它放在它上面#root将无效).

  6. package.json用Parcel 替换你的CRA 任务:

从中更改脚本

"scripts": {
  "start": "react-scripts start",
  "build": "react-scripts build",
  "test": "react-scripts test --env=jsdom",
  "eject": "react-scripts eject"
}
Run Code Online (Sandbox Code Playgroud)

"scripts": {
  "start": "parcel src/index.html",
  "prebuild": "rm -rf dist/",
  "build": "parcel build src/index.html"
}
Run Code Online (Sandbox Code Playgroud)

包裹没有eject,有没有test.您startbuild命令都会将文件输出到您的dist文件夹,这就是为什么在构建之前删除它是个好主意.此外,添加.cache/dist你的.gitignore.

而已.如果我错过任何事情,请告诉我.

  • 我还必须添加带有{“ presets”:[“ react-app”]}的.babelrc文件并安装这些预设:npm install --save-dev babel-preset-react-app (3认同)