在React中使用CloudKit

问题

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

方案

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

具体步骤如下:
index.html中


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/

你可能感兴趣的:(在React中使用CloudKit)