ckeditor5-react icon indicating copy to clipboard operation
ckeditor5-react copied to clipboard

Test suite failed: import Editor from '@ckeditor/ckeditor5-core/src/editor/editor';

Open AnJooCo opened this issue 4 years ago • 5 comments

Hey guys,

I keep having troubles with my ckeditor integration. I used the build from source version, like discribed here but in an exsiting project -> so I started with adding the packages and modifying webpack. The integration seems to be working good, but when I run my tests, then I getting and error, where I can't find the reason.

The tests are done with jest and only failing when I implement the built from source. I also tested the ready to use classic-build, but seem to work fine. Details of the error and code are described below

The full error message says: `● Test suite failed to run

***/node_modules/@ckeditor/ckeditor5-editor-classic/src/classiceditor.js:10
import Editor from '@ckeditor/ckeditor5-core/src/editor/editor';
       ^^^^^^

SyntaxError: Unexpected identifier`

What I was doing: 1.) Implemented the editor (config settings in a seperate file)

import CKEditor from '@ckeditor/ckeditor5-react';
import ClassicEditor from '@ckeditor/ckeditor5-editor-classic/src/classiceditor';
import EditorConfig from './EditorConfig';

const CkEditor = ({ handleStateChanges, contentText, placeholderText }) =>{
  let editorLanguage = navigator.language.slice(0, 2).toLowerCase();
  return (
    <CKEditor
      editor={ClassicEditor}
      config={EditorConfig({ editorLanguage, placeholderText })}
      data={contentText || ''}
      onInit={editor =>{}}
      onChange={(event, editor) =>{
        const data = editor.getData();
        handleStateChanges('contentText', data);
      }} />
  );};

2.) set up the config

import Essentials from '@ckeditor/ckeditor5-essentials/src/essentials';
import Autoformat from '@ckeditor/ckeditor5-autoformat/src/autoformat';
import Bold from '@ckeditor/ckeditor5-basic-styles/src/bold';
import Italic from '@ckeditor/ckeditor5-basic-styles/src/italic';
import BlockQuote from '@ckeditor/ckeditor5-block-quote/src/blockquote';
import CKFinder from '@ckeditor/ckeditor5-ckfinder/src/ckfinder';
import Heading from '@ckeditor/ckeditor5-heading/src/heading';
import Link from '@ckeditor/ckeditor5-link/src/link';
import List from '@ckeditor/ckeditor5-list/src/list';
import MediaEmbed from '@ckeditor/ckeditor5-media-embed/src/mediaembed';
import Paragraph from '@ckeditor/ckeditor5-paragraph/src/paragraph';
import PasteFromOffice from '@ckeditor/ckeditor5-paste-from-office/src/pastefromoffice';
import Table from '@ckeditor/ckeditor5-table/src/table';
import TableToolbar from '@ckeditor/ckeditor5-table/src/tabletoolbar';
import TextTransformation from '@ckeditor/ckeditor5-typing/src/texttransformation';
import Alignment from '@ckeditor/ckeditor5-alignment/src/alignment';
import Strikethrough from '@ckeditor/ckeditor5-basic-styles/src/strikethrough';
import Underline from '@ckeditor/ckeditor5-basic-styles/src/underline';

const EditorConfig = ({ editorLanguage, placeholderText }) => ({
  //language: editorLanguage, 
  link: { addTargetToExternalLinks: true },
  mediaEmbed: {
    previewsInData: true,
  },
  placeholder: placeholderText,
  plugins: [ Essentials, Autoformat, Bold, Italic, Underline, Strikethrough, Alignment, BlockQuote,
CKFinder, Heading, Link, List, MediaEmbed, Paragraph, PasteFromOffice, Table, TableToolbar, TextTransformation ],
  toolbar: [ 'heading', '|', 'bold', 'italic', 'underline', 'strikethrough', 'link', '|', 'alignment', 'bulletedList', 'numberedList', '|', 'blockQuote', 'insertTable', 'mediaEmbed', '|', 'undo', 'redo',
  ],
  table: {
    contentToolbar: ['tableColumn', 'tableRow', 'mergeTableCells'],
  },
});
export default EditorConfig;

Thats what I did, but checking my code and other error reports, did let me figure out why that happens. I checked my packages.json

  • jest & babel-jest having the same version number.
  • The transform definitions, seem to fine (compared to what was recommended). Here the code.
"transform": {
      "^.+\\.(js|jsx|ts|tsx)$": "<rootDir>/node_modules/babel-jest",
      "^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
      "^(?!.*\\.(js|jsx|ts|tsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
    },
    "moduleNameMapper": {
      ".*\\.(css|less|scss)$": "identity-obj-proxy",
      ".*\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "babel-jest"
    },
    "transformIgnorePatterns": [
      "[/\\\\]node_modules[/\\\\].+\\.(js|jsx|ts|tsx|css|sass|scss|less)$"
    ]

And now the biggest part, the webpack. I have to admid, I haven't worked with webpack before, and most of it was already their. So I migth have missed something here. But I did try to add the settings, like meanted in the description above, only with the problem that the part with the loader: 'style-loader' intest: /ckeditor5-[^/\\]+[/\\]theme[/\\].+\.css$/, allways had some problems. I completely removed that part, after seen that the s?css allready set the style-loader and the problems where gone.

Full config:

const path = require('path');
const webpack = require('webpack');
const TerserPlugin = require('terser-webpack-plugin');
const FilterWarningsPlugin = require('webpack-filter-warnings-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackTemplate = require('html-webpack-template');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const packageJson = require('./package.json');
const DuplicatePackageCheckerPlugin = require('duplicate-package-checker-webpack-plugin');
const serverConfig = require('./config/serverConfig');

const antVars = require('./ant-theme-vars');
const { styles } = require('@ckeditor/ckeditor5-dev-utils');
const CKEditorWebpackPlugin = require('@ckeditor/ckeditor5-dev-webpack-plugin');

module.exports = (env, argv) => {
  process.env.NODE_ENV =
     argv.mode === 'production' ? 'production' : 'development';
  const isProduction = process.env.NODE_ENV === 'production';
  const stats = {
     all: false,
     modules: true,
     maxModules: 0,
     errors: true,
     warnings: true,
     moduleTrace: true,
     errorDetails: true,
   };
 
   return {
     module: {
       strictExportPresence: true,
       rules: [ {
           test: /\.jsx?$/,
           use: [ { loader: 'babel-loader' } ] },
         {
           test: /\.less$/,
           use: [ isProduction ? MiniCssExtractPlugin.loader : 'style-loader',
             'css-loader',
             'postcss-loader',
             { loader: 'less-loader',
               options: { javascriptEnabled: true, modifyVars: antVars } } ],
         },
         { test: /\.s?css$/,
           use: [ isProduction ? MiniCssExtractPlugin.loader : 'style-loader',
             'css-loader', 'postcss-loader', 'sass-loader' ] },
         { test: /\.(ttf|eot|woff2?|svg)$/,
           use: [ {
               loader: 'file-loader',
               options: { name: 'fonts/[name].[ext]' } }  ],
             // for the ckeditor: Exclude `js` files to keep the "css" loader working as it injects
             // its runtime that would otherwise be processed through the "file" loader.
             // Also exclude `html` and `json` extensions so they get processed
             // by webpack's internal loaders.
           exclude: [
             /\.(js|mjs|jsx|ts|tsx)$/,
             /\.html$/,
             /\.json$/,
             /ckeditor5-[^/\\]+[/\\]theme[/\\]icons[/\\][^/\\]+\.svg$/,
             /ckeditor5-[^/\\]+[/\\]theme[/\\].+\.css/,
           ],
         },
         {
           test: /\.(png|jpe?g|gif)$/,
           use: [ {
               loader: 'url-loader',
               options: {
                 limit: 8192,
                 name: 'images/[name].[ext]' },
             }, 'img-loader' ],
         },
         {
           test: /ckeditor5-[^/\\]+[/\\]theme[/\\]icons[/\\][^/\\]+\.svg$/,
           use: ['raw-loader'],
         },
         {
           test: /ckeditor5-[^/\\]+[/\\]theme[/\\].+\.css$/,
           use: [ {
               loader: 'postcss-loader',
               options: styles.getPostCssConfig({
                 themeImporter: {
                   themePath: require.resolve('@ckeditor/ckeditor5-theme-lark'),
                 },
                 minify: true}) } ] } ] },
     devtool: !isProduction && 'sourcemap',
     devServer: {
       stats,
       port: 9080,
       hot: true,
       contentBase: './src',
       publicPath: '/',
       proxy: {
         '/socket.io/*': {
           target: serverConfig.targetServerUrl....,
           ws: true,
           changeOrigin: true,
         },
         '/rest/*': {
           target: serverConfig.targetServerUrl.....,
           ws: false,
           changeOrigin: true,
         },
         '/api/*': {
           target: serverConfig.targetServerUrl.....,
           ws: true,
           changeOrigin: true } },
     },
     optimization: {
       minimizer: [
         new TerserPlugin({
           parallel: true,
         }),
       ],
       splitChunks: {
         cacheGroups: {
           vendor: { name: 'vendor',
             chunks: 'initial',
             test: /node_modules/,
             priority: 20 },
           common: { name: 'common',
             minChunks: 2,
             chunks: 'async',
             priority: 10,
             enforce: true } } },
       runtimeChunk: 'single',
     },
     plugins: [
       isProduction && new DuplicatePackageCheckerPlugin(),
       new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /de|en/),
       isProduction && new webpack.HashedModuleIdsPlugin(),
       // Silence mini-css-extract-plugin generating lots of warnings for CSS ordering.
       // We use CSS modules that should not care for the order of CSS imports, so we
       // should be safe to ignore these.
       //
       // See: https://github.com/webpack-contrib/mini-css-extract-plugin/issues/250
       new FilterWarningsPlugin({
         exclude: /mini-css-extract-plugin[^]*Conflicting order between:/,
       }),
       isProduction && new CleanWebpackPlugin(['dist']),
       isProduction &&
         new CopyWebpackPlugin([{ from: 'src/assets', to: 'assets' }]),
       new webpack.HotModuleReplacementPlugin(),
       new webpack.DefinePlugin({
         'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
         'process.env.DEBUG': JSON.stringify(process.env.DEBUG),
         'process.env.LOCAL': JSON.stringify(process.env.LOCAL),
         NODE_ENV: JSON.stringify(process.env.NODE_ENV),
         DEBUG: JSON.stringify(process.env.DEBUG),
         VERSION: JSON.stringify(packageJson.version),
       }),
       new HtmlWebpackPlugin({
         inject: false,
         template: HtmlWebpackTemplate,
         minify: isProduction && {
           removeComments: true,
           collapseWhitespace: true },
         title: '...',
         appMountId: 'target',
         mobile: true,
         favicon: './src/assets/icons/favicon.ico',
         links: [{
             href: '/assets/icons/touchicons/....png',
             rel: 'apple-touch-icon',
             sizes: '180x180' },
           { href: '/assets/icons/touchicons/....png',
             rel: 'apple-touch-icon',
             sizes: '152x152' }m],
       }),
       new MiniCssExtractPlugin({
         // Options similar to the same options in webpackOptions.output
         // both options are optional
         filename: '[name][contenthash:6].css',
         chunkFilename: '[id].[chunkhash:6].css',
       }),
       process.env.ANALYZE && new BundleAnalyzerPlugin(),
       new CKEditorWebpackPlugin({
         language: 'en',
       }),
     ].filter(x => x),
     entry: ['@babel/polyfill', './src/client.js'],
     output: {
       filename: isProduction ? 'client.[hash:6].js' : 'client.js',
     },
     resolve: {
       alias: {
         // fix duplicate modules
         moment: path.resolve(__dirname, 'node_modules/moment'),
         react: path.resolve(__dirname, 'node_modules/react'),
       },
      extensions: [  '.web.js', '.client.js', '.js', '.json'],
     },
     node: {
       fs: 'empty',
       net: 'empty',
       tls: 'empty',
 }};};

Does anyone has a idea why that error happens and how to solve it?

AnJooCo avatar Apr 17 '20 04:04 AnJooCo

Hi, thanks for the report. Unfortunately I can confirm that. I created a fresh project following docs on building from source and as soon as I ran some simple tests I got:

import Editor from '@ckeditor/ckeditor5-core/src/editor/editor';
           ^^^^^^

    SyntaxError: Unexpected identifier

      4 | 
      5 | // NOTE: Use the editor from source (not a build)!
    > 6 | import ClassicEditor from '@ckeditor/ckeditor5-editor-classic/src/classiceditor';
        | ^
      7 | 
      8 | import Essentials from '@ckeditor/ckeditor5-essentials/src/essentials';
      9 | import Bold from '@ckeditor/ckeditor5-basic-styles/src/bold';

      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)
      at Object.<anonymous> (src/App.js:6:1)

cc @pomek could you take a look at this?

FilipTokarski avatar Apr 21 '20 11:04 FilipTokarski

Hello @AnJooCo – you should be able to configure Jest to transpile CKEditor 5. See here or here.

jodator avatar Apr 22 '21 14:04 jodator

Also see: https://github.com/ckeditor/ckeditor5-react/issues/225.

pomek avatar Apr 22 '21 14:04 pomek

Also see: #225.

Oh, that's an even better one. Pitty that it wasn't the first result in a web search :upside_down_face: I wouldn't have to dig into Jest documentation :D

jodator avatar Apr 22 '21 14:04 jodator

Hi How can we style placeholder text, especially to reduce the font size and font family

https://codesandbox.io/s/festive-nova-l4zo5?file=/src/App.js can some one help in modifying the size of placeholder text

akhilsarasan avatar Nov 03 '21 08:11 akhilsarasan