在React中使用CloudKit

问题

CloudKit js是苹果为web应用推出的CloudKit API。可惜,通过create-react-app 创建的工程直接引用CloudKit JS时不能解析它,直接报错: define is not defined ...

方案

通过webpack引入外部模块的方式来引入CloudKitjs。这样CloudKit不由Webpack编译,也不会打包到bundle.js中。

具体步骤如下:
index.html中

<script src="https://cdn.apple-cloudkit.com/ck/2/cloudkit.js"></script>

webpack.config.js (webpack.config.dev.js或者webpack.config.prod.js)中

module.exports = {

  externals: {
    CloudKit: 'CloudKit'
  }, 
...
  entry: [
    // Include an alternative client for WebpackDevServer. A client's job is to
    // connect to WebpackDevServer by a socket and get notified about changes.
    // When you save a file, the client will either apply hot updates (in case
    // of CSS changes), or refresh the page (in case of JS changes). When you
    // make a syntax error, this client will display a syntax error overlay.
    // Note: instead of the default WebpackDevServer client, we use a custom one
    // to bring better experience for Create React App users. You can replace
    // the line below with these two lines if you prefer the stock client:
    // require.resolve('webpack-dev-server/client') + '?/',
    // require.resolve('webpack/hot/dev-server'),
    require.resolve('react-dev-utils/webpackHotDevClient'),
    ...
    require.resolve('./cloudkit'), 

在使用时直接像module一样引用即可:

import CloudKit from 'CloudKit';

参考

https://webpack.js.org/configuration/externals/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • webpack 介绍 webpack 是什么 为什么引入新的打包工具 webpack 核心思想 webpack 安...
    yxsGert阅读 6,496评论 2 71
  • GitChat技术杂谈 前言 本文较长,为了节省你的阅读时间,在文前列写作思路如下: 什么是 webpack,它要...
    萧玄辞阅读 12,710评论 7 110
  • 版权声明:本文为博主原创文章,未经博主允许不得转载。 webpack介绍和使用 一、webpack介绍 1、由来 ...
    it筱竹阅读 11,223评论 0 21
  • 目录第1章 webpack简介 11.1 webpack是什么? 11.2 官网地址 21.3 为什么使用 web...
    lemonzoey阅读 1,751评论 0 1
  • 土地——写给我故乡的诗 你扎根泥土的深情 二十来年,一如往日 三月的杨柳曾衣你,以翠色华裳 十月的白雪,也沧桑你鬓...
    苏未溪阅读 370评论 0 0