GithubHelp home page GithubHelp logo

contentful / create-contentful-extension Goto Github PK

View Code? Open in Web Editor NEW
71.0 59.0 14.0 4.86 MB

Create Contentful Extension is a CLI tool for developing in-app extensions without the hassle of managing build configurations.

License: MIT License

JavaScript 70.63% CSS 0.21% HTML 0.62% TypeScript 28.55%

create-contentful-extension's Introduction

We recommend create-contentful-app over this repo

For new projects, please use the create-contentful-app cli.

Using apps will allow you to use the latest features, and up to date versions of our other open source libraries.

Create Contentful Extension PRs Welcome

Create Contentful Extension is a CLI tool for developing in-app extensions without the hassle of managing build configurations.

If something doesn’t work, please file an issue.

Quick Overview

npx @contentful/create-contentful-extension my-first-extension
cd my-first-extension
npm install
npm run login && npm run configure
npm run start

Requirements

  • Node 12.13 or higher
  • NPM 6.12.0 and higher

What’s Included?

Your environment will have everything you need to build a modern Contentful UI Extension with React:

  • React, JSX, ES6, TypeScript and all that supported by Parcel
  • Forma 36 - React component library for Contentful design system.
  • A live development server with hot reload.
  • A build script to bundle JS, CSS, and images for production by inlining everything to srcdoc

Despite the fact that we encourage you to use React + Forma36 for building extensions, you can pick any framework and use it as you would use it with Parcel bundler.

Get Started Immediately

You don’t need to install or configure tools like Webpack or Babel.
They are preconfigured and hidden so that you can focus on the code.

We use Parcel bundler under the hood and you can use all assets that are supported there with no additional configuration.

Creating an extension

npx @contentful/create-contentful-extension my-first-extension

It will ask you what type of extension you want to create (read about different types of extensions):

Then npm will install all required development and production dependencies and create a directory called my-first-extension inside the current folder.

Inside that directory, it will generate the initial project structure:

my-first-extension
├── node_modules
├── .babelrc
├── .contentfulrc.json
├── .gitignore
├── package.json
├── extension.json
└── src
    ├── index.html
    ├── index.js
    └── index.css

Once the installation is done, you can open your project folder:

cd my-first-extension
# install dependencies
npm install
# login to contentful
npm run login
# select what space and enviroment you'll be using for development and deployment
npm run configure
# starts development server and publishes the extension in a development mode
npm run start

When the development server is up and running open https://app.contentful.com.

Go to Settings -> Extensions to verify that extension is installed in a development mode.

Go to Content model configuration.

Select a field in the Content Type. Navigate to Settings > Appearance of the field. Assign the extension to a field.

Go to the content of this Content Type and enable mixed content at your browser so that development version that is served from your local machine could be rendered within https://app.contentful.com.

Commands

npm run start

Starts the development server and deploys the extension in development mode.

The extension will automatically reload if you make changes to the code.

npm run build

Builds the extension for production to the build folder.
It correctly bundles React and all dependencies in production mode and optimizes the build for the best performance.

npm run test

Run jest runner in watch mode. Passes through all flats directly to Jest. If you happen to have a local jest configuration file (i.e: jest.config.js), testing only supports exporting a config object (as opposed to functions).

npm run login

Starts new session with our CLI. As the CLI tool uses our Content Management API, you need to have an CMA access token to use all the commands.

npm run logout

Ends your current session with the CLI tool.

npm run configure

Asks which space and environment you want to use for development and deployment. It saves your answers to local .contentfulrc.json.

Caution: Do not commit .contentfulrc.json to your repository. It contains sensitive information and intended to be used only on your local machine.

npm run deploy

Bundles the extension for production and deploys bundled version to Contentful.

npm run help

Shows help information about create-contentful-extension.

FAQ

I want to use test environment for during the development. How can I set it up?

Use npm run configure command. It asks what space and environment you'd like to use. The answers are saved in .contentfulrc.json file, located next to package.json.

Caution: Do not commit .contentfulrc.json to your repository. It contains sensitive information and intended to be used only on your local machine.

I want to serve the extension in development mode from a custom port number (not default 1234). Is it possible?

Yes, it's possible. Edit start scripts in package.json file according to the following example:

"start": "contentful-extension-scripts start --port 8000",

I want to serve the extension without creating/updating the extension via the CLI

If you simply want to serve the extension without having the CLI create or update an extension in your space, you can add --serve-only to the start command.

"start": "contentful-extension-scripts start --serve-only",

Available since v0.14.0

I'm using development mode but my extension is not showing up. What's wrong?

In development mode, extension is served from http://localhost:1234, but app.contentful.com is loaded via https protocol which leads the browser to prevent mixed content. While doing development you need to click Load unsafe scripts (Chrome) to enable serving extension from http://localhost.

I'm not the biggest fan of disabling the mixed content setting in browsers. Can I use HTTPS in development mode?

Yes, you can serve your extension using HTTPS. Add --https to start command.

"start": "contentful-extension-scripts start --https",

It uses Parcel HTTPS under the hood , which generates a self-signed certificate, you might have to configure your browser to allow self-signed certificates for localhost.

I generated my extension with create-contentful-extension several months ago but I'd like to use features that became available later. How can I upgrade?

Just update @contentful/contentful-extension-scripts dependency in your package.json to the latest one and check Releases to see if there were any breaking changes. Follow the instructions there.

My extension is bigger than 512Kb. How can I deploy it for production usage?

You can't use Hosted by Contentful (srcdoc) hosted extension if the extension is bigger than 512Kb. But you can serve extension from any server using src property.

Instead of using npm run deploy, add --no-inline to build command:

"build": "contentful-extension-scripts build --no-inline"

It generates minified and production-ready version of your extension. Upload build folder to GitHub pages, Netlify or any other hosting and use Self-hosted (src) option to serve the extension from your own domain.

Contributing

We'd love to have your helping hand on create-contentful-extension!

License

Create Contentful Extension is open source software licensed as MIT.

create-contentful-extension's People

Contributors

andipaetzold avatar anho avatar connor-baer avatar davidfateh avatar dependabot-preview[bot] avatar dependabot[bot] avatar jwhiles avatar kdamball avatar kitos avatar kuznetsovnikita avatar lehnerm avatar maling avatar michelbitter avatar scnroy avatar suevalov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

create-contentful-extension's Issues

Detect compare mode for contentful app

Issue

Hi, I created Contentful app with my own Markdown Editor, with some feature then required by customer.

How I can detect that app will run in compare page?

So that I can display the content in preview mode, in full height.
I don't can find any flags or kinds in code, and I don't can find any documentation about this.

I init my app like this:

import { MarkdownEditor, renderMarkdownDialog } from 'field-editor-markdown';

init(sdk => {
  if (sdk.location.is(locations.LOCATION_DIALOG)) {
    render(renderMarkdownDialog(sdk), document.getElementById('root'));
  } else if (sdk.location.is(locations.LOCATION_ENTRY_FIELD)) {
    render(<MarkdownEditor sdk={sdk} />, document.getElementById('root'));
  }
});

Thanks.

Insecure content warning in development

Expected Outcome

The extension should load in Contentful when running it with npm run start.

Actual Outcome

The extension does not load and an error message is displayed in the console:

Blocked loading mixed active content “http://localhost:1234/”

Steps To Reproduce

  1. Create a new extension with the CLI
  2. Run npm run start
  3. Try to load an entry that contains the UI extension and check the console for errors.

System information

Operating system + version: macOS 10.14.3 beta
Browser + version: Firefox Developer Edition 66.0b5

Screenshots

Console error:

screenshot 2019-03-01 23 57 09

UI Extension:

screenshot 2019-03-01 23 57 22

@contentful\contentful-extension-scripts Missing from node_modules on Windows 10

After executing

cd contentful-deep-copy-extension
npm install && npm run login && npm run configure && npm run start

I get the following error:

> [email protected] start D:\devprojects\contentful-deep-copy-extension
> contentful-extension-scripts start

internal/modules/cjs/loader.js:969
    throw err;
    ^

Error: Cannot find module 'D:\devprojects\contentful-deep-copy-extension\node_modules\@contentful\contentful-extension-scripts\lib\index.js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:966:17)
    at Function.Module._load (internal/modules/cjs/loader.js:859:27)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `contentful-extension-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

A quick check of node_modules confirms there is no @contentful\contentful-extension-scripts path in node_modules.

image

System: windows 10
Extension type: sidebar
Tried node versions 13.5.0 and 11.15.0

Building extensions does not support tsconfig `extends` property

I am using the contentful-extensions-scripts start command but have found that it is using Parcel version 1.x. It is a known bug that Parcel version 1 does not support tsconfig extends see this article.

There is a workaround currently that is to copy the compilerOptions from the parent tsconfig to the child (aka the extensions I am building) but would rather raise this as an issue as there is no dialogue to identify that the extended compiler options are not working.

Version Mismatch of with @contentful/field-editor-reference causing TypeScript errors

The create-contentful-extension CLI seems to install contentful-ui-extensions-sdk v3.13.0 (link).

The @contentful/field-editor-reference library installs (at least) v3.18.0 (link).

When using the two in conjunction in TypeScript, there are typing errors with the sdk prop from the App. Since the two versions of the sdk library have different definitions for BaseExtensionsSDK.

I wouldn't know the implications, but it would be nice if the CLI could match the version of the field editor library, which is expected to be used in conjunction with it.

How to pass env variables to the extension?

Hi there,

I need to define some env variables for dev/qa/production build system driven by Jenkins.

Actually we build extensions using Webpack, and we use the Define plugin:

 new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(mode),
        PACKAGE_NAME: JSON.stringify(packageJson.name),
        PACKAGE_VERSION: JSON.stringify(packageJson.version),
        BUILD_NUMBER: JSON.stringify(process.env.BUILD_NUMBER),
        MULE_BASE_URL: JSON.stringify(process.env.MULE_BASE_URL),
        CENTRAL_ASSET_ID: JSON.stringify(process.env.CENTRAL_ASSET_ID)
      }
    }),

but I don't understand how I can do this with your scripts.

Thanks,
Vincenzo

Unhandled Promise Rejection on run build

Description

Issue

I create a misprint at import file.
The script did not end, hung.
got this:

yarn run v1.22.4
$ contentful-extension-scripts build --no-inline
🚨  /packages/custom-editor/src/index.tsx:11:28: Cannot resolve dependency './componentss' at '/packages/custom-editor/src/componentss'
    at Resolver.resolve (/node_modules/parcel-bundler/src/Resolver.js:71:17)
    at async Bundler.resolveAsset (/node_modules/parcel-bundler/src/Bundler.js:433:18)
    at async Bundler.resolveDep (/node_modules/parcel-bundler/src/Bundler.js:484:14)
    at async /node_modules/parcel-bundler/src/Bundler.js:608:26
    at async Promise.all (index 8)
(node:5347) UnhandledPromiseRejectionWarning: Error: Cannot resolve dependency './componentss' at '/packages/custom-editor/src/componentss'
    at Resolver.resolve (/node_modules/parcel-bundler/src/Resolver.js:71:17)
    at async Bundler.resolveAsset (/node_modules/parcel-bundler/src/Bundler.js:433:18)
    at async Bundler.resolveDep (/node_modules/parcel-bundler/src/Bundler.js:484:14)
    at async /node_modules/parcel-bundler/src/Bundler.js:608:26
    at async Promise.all (index 8)
(node:5347) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:5347) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

We use mono-repository and lerna.
Out build didn't stop, and succesly finish.

Using:

node: v12.16.2
yarn: v1.22.4

Expected behavior

Script should stop process at UnhandledPromiseRejectionWarning

Blank page without errors.

I created an example extension but get an blank page.

The dev and build versions are affected.

Looks like the init method in index.js will not fired at all. The CORS problem seems not related because i don't get an shield icon in chrome. Also installed an CORS addon in firefox with no effect.

A colleague has the same issue. We both working with Linux. Tested it on a mac with the same result.

In our network only port 80 and 443 are allowed. Could this be a problem?

No content from my UI extension in app.contentful.com

Just a tip:

After a long search what might have been the problem of receiving no content at all in my custom UI extension;

The mixed content error can be solved by simply running over https (in scripts):
"start": "HTTPS=true contentful-extension-scripts start"

The other problem I had: I didn't receive any content from my dev-UI-extension, I fixed it by changing my index.html like this;
image

Rule 5 & 6 were not included in the $ npx @contentful/create-contentful-extension and this fixed my problem of no content.

Cannot find module on start

Following your setup instructions, i'm running into an issue where when i run npm run start i get an error complaining that the following module couldn't be found: \node_modules\@contentful\contentful-extension-scripts\lib\index.js

Running 0.36.0 of the contentful cli & node v10.16.1

Line number missing from stack trace

a UI Extension rendering in different locations is throwing an exception because

state = {
    value: this.props.sdk.field.getValue()
  }

does not exist when the extension is render in the sidebar. In the stack trace, I would expect an error which links to the line where the problem occurs:

image (1)

Possibility to specify build directory

Is it possible to create a build-script in which you can specify which folder it has to build?

My script now:
"build": "contentful-extension-scripts build"

But then I get a Parcel-error: No entries found.

My project-structure e.g. :

root
   node_modules/
   package.json
   extensions/
      barcode-checker/
         src/
            index.js
            index.html
            index.css
         extension.json

zlib usage

I tried to develop a new ui-extension with cli support. I followed these instructions to do so.

when running npm install i get the following error

npm ERR! path <path-to-generated-extension-project>\<extension-name>\node_modules\zlib
npm ERR! command failed
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c node-waf clean || true; node-waf configure build
npm ERR! Der Befehl "node-waf" ist entweder falsch geschrieben oder
npm ERR! konnte nicht gefunden werden.
npm ERR! Der Befehl "true" ist entweder falsch geschrieben oder
npm ERR! konnte nicht gefunden werden.
contentful -v
1.12.15

node -v
v16.14.0

npm -v
8.5.3

OS System: windows 10

Any idear how to work aroung this? I would really like to have full use of this tool.

Thx!

React Dev Tools

Hello 👋

I'm pretty new to React so forgive me if this is the wrong place for this, but I'm trying to use React Dev Tools with a Contentful CLI extension and coming up short.

I've done some googling and tried to add this to the index.html file

<script> __REACT_DEVTOOLS_GLOBAL_HOOK__ = parent.__REACT_DEVTOOLS_GLOBAL_HOOK__ </script>

However, that triggers

Uncaught DOMException: Blocked a frame with origin "https://localhost:1234" from accessing a cross-origin frame.
    at https://localhost:1234/:5:53
(anonymous) @ (index):5

Within Contentful. Surely there must be a way to use React Dev Tools for a CLI extension?

Thanks for the guidance!

Support deployment to subfolders

I currently have to manually remove slashes from build files before pushing since we are deploying to subfolders in github pages. It would be nice to have an option to specify an asset root URL in the package.json or in a config file.

Here's my currentl build process:

cd {extension}
npm run build

<!DOCTYPE html>
<html>
  <head>
    <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
    <meta charset="utf-8">
  -<link rel="stylesheet" href="/src.e31bb0bc.css"></head>
  +<link rel="stylesheet" href="src.e31bb0bc.css"></head>
  <body>
    <div id="root"></div>
    <script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
    -<script type="text/javascript" src="/src.e31bb0bc.js"></script>
    +<script type="text/javascript" src="src.e31bb0bc.js"></script>
  </body>
</html>

cd ..
git commit -m "some message"
git push master

Upgrade dependency htmlnano to v1.0.0 to fix transitive security vulnerability

htmlnano < 1.0.0 has a transitive security vulnerability from postcss. Details about the security vulnerability: GHSA-hwj9-h5mp-3pm3

 => Found "purgecss#[email protected]"
 info This module exists because "_project_#@contentful#contentful-extension-scripts#htmlnano#purgecss" depends on it.

htmlnano upgraded their dependency to the patched version in: posthtml/htmlnano@f05c780 (purgecss updated their dependency starting in v3.1.0, see FullHuman/purgecss@72302ff)

Please upgrade the htmlnano dependency to v1.0.0 or higher.

On Hot Reload, `getValue()` returns initial entry values instead of current values

There’s a bug with create-cotentful-ui-extension with hot reload where on hot reload, any fields that were modified since the last time you loaded the page show the original value when you call entry.fields[field].getValue(). This is particularly annoying for developing UI extensions that modify fields and kind of defeats the purpose of hot reload.
repro: create an extension using create-contentful-extension and in the constructor, throw in
console.log('value:', props.sdk.entry.fields[whateverTheFieldIs].getValue().
Uncomment the hot reload code.
Say you create a new entry with this extension set up. On load, it should log value: undefined. type something like ‘asdf’ in the field. Save your index.js so it hot reloads.
Expected: console should log value: 'asdf'
Actual: console logs ’value: undefined`
If you now refresh the page, then the console logs value: 'asdf'. Edit the field to be ‘asdfasdf’ then save your index.js
Expected: console should log value: 'asdfasdf'
Actual: console logs value: 'asdf'

Issue with UI extension creation

Hi There,

I'm trying to create a UI extension using create UI extension CLI which is not working. I'm getting the following error when I try to run the dev env

Screenshot 2020-05-07 at 6 16 29 PM

I'm imagining that this is something to do with how the SDK is getting initiated. Any help would be greatly appreciated!

Failed to load resource: the server responded with a status of 404 ()
api.contentful.com/spaces/xxxxx/ui_config:1 

Thanks!

Remember which space I am using

I think it would be great to remember my last used space. When I switch between develop, build and deploy I dont want to re-choose my space all the time.

Need to restart dev server in an unpredictable time.

I have to restart the dev server in an unpredictable way after i made changes.

So, for example:

  • edit a string
  • safe changes
  • server rebuilds
  • switch to browser and see the changes.

After a second change, nothing of the above is working. I have to restart the server by hand and reload the page.

In package.json scripts i only changed the space and env id, because i need to work in a different env.

Allow overriding publicUrl

Hi! We'll be creating several Contentful extensions which we plan to host ourselves. However, currently Parcel's publicUrl is set to ./ for all builds, which is effectively baring us from deploying multiple extensions in separate folders on the same domain(the CSS and JS files will always be assumed to exist at the domain root)

We can always monkey-patch the paths in the build artefacts I suppose, although we would prefer a cleaner solution of course.

Feature: support code reuse for multiple-extension repos

First of all, thanks for this extremely useful tool!

We've started to use extensions a lot. One consequence of this is that our extension repo now has tons of duplicate code . On average probably something like 70% - 80% of the code for each extension is shared with the other ones (for instance we have three very similar extensions that each have something like 5 unique lines).

In a regular webpack project we'd solve this by putting common utilities and components in a folder beside the individual extension folders, and configure webpack to resolve node_modules from within the respective extension folders. This does not work with contentful-extension-scripts – the build crashes because node_modules can't be resolved for files that are not beside or below package.json in the file tree.

For babel it seems sufficient to rename .babelrc to babel.config.json to enable transpilation of files outside of the root folder. I'm not familiar with Parcel, so I don't know whether this is even possible, and even if it were possible I see no documented way of passing configuration to Parcel.

Duplicating so much code for each new extension does not scale well. Having support (or a documented workaround) for code reuse would be a really great addition!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.