React-date-picker: Webpack compilation error: Unexpected token . on ".react-calendar"

Created on 20 Apr 2018  Â·  14Comments  Â·  Source: wojtekmaj/react-date-picker

Hey guys, I recently upgraded to React 16, in a project based off of an earlier version of React Starter Kit. this lead me to upgrade react-date-picker which I am now getting the following error:

C:\workspace\cand-portal-front\node_modules\react-calendar\dist\Calendar.css:1
(function (exports, require, module, __filename, __dirname) { .react-calendar {
                                                              ^

SyntaxError: Unexpected token .
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:599:28)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Module.require (module.js:579:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (C:\workspace\cand-portal-front\node_modules\react-date-picker\dist\entry.js:7:1)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Module.require (module.js:579:17)

Looks like it could be similar to whats expressed here: https://github.com/reactGo/reactGo/issues/850#issuecomment-299417219

my full webpack config is:

import path from 'path';
import webpack from 'webpack';
import extend from 'extend';
import AssetsPlugin from 'assets-webpack-plugin';

const isDebug = !process.argv.includes('--release');
const isVerbose = process.argv.includes('--verbose');

//
// Common configuration chunk to be used for both
// client-side (client.js) and server-side (server.js) bundles
// -----------------------------------------------------------------------------

const config = {
  context: path.resolve(__dirname, '../src'),

  output: {
    path: path.resolve(__dirname, '../build/public/assets'),
    publicPath: '/assets/',
    sourcePrefix: '  ',
  },

  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        include: [
          path.resolve(__dirname, '../src'),
        ],
        query: {
          // https://github.com/babel/babel-loader#options
          cacheDirectory: isDebug,

          // https://babeljs.io/docs/usage/options/
          babelrc: false,
          presets: [
            // Latest stable ECMAScript features
            // https://github.com/babel/babel/tree/master/packages/babel-preset-latest
            'latest',
            // Experimental ECMAScript proposals
            // https://github.com/babel/babel/tree/master/packages/babel-preset-stage-0
            'stage-0',
            // JSX, Flow
            // https://github.com/babel/babel/tree/master/packages/babel-preset-react
            'react',
            ...isDebug ? [] : [
              // Optimize React code for the production build
              // https://github.com/thejameskyle/babel-react-optimize
              'react-optimize',
            ],
          ],
          plugins: [
            // Externalise references to helpers and builtins,
            // automatically polyfilling your code without polluting globals.
            // https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-runtime
            'transform-runtime',
            ...!isDebug ? [] : [
              // Adds component stack to warning messages
              // https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-react-jsx-source
              'transform-react-jsx-source',
              // Adds __self attribute to JSX which React will use for some warnings
              // https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-react-jsx-self
              'transform-react-jsx-self',
            ],
          ],
        },
      },
      {
        test: /\.css/,
        loaders: [
          'isomorphic-style-loader',
          `css-loader?${JSON.stringify({
            // CSS Loader https://github.com/webpack/css-loader
            importLoaders: 1,
            sourceMap: isDebug,
            // CSS Modules https://github.com/css-modules/css-modules
            modules: true,
            localIdentName: isDebug ? '[name]-[local]-[hash:base64:5]' : '[hash:base64:5]',
            // CSS Nano http://cssnano.co/options/
            minimize: !isDebug,
          })}`,
          'postcss-loader?pack=default',
        ],
      },
      {
        test: /\.scss$/,
        loaders: [
          'isomorphic-style-loader',
          `css-loader?${JSON.stringify({ sourceMap: isDebug, minimize: !isDebug })}`,
          'postcss-loader?pack=sass',
          'sass-loader',
        ],
      },
      {
        test: /\.json$/,
        loader: 'json-loader',
      },
      {
        test: /\.txt$/,
        loader: 'raw-loader',
      },
      {
        test: /\.graphqls$/,
        loader: 'raw-loader',
      },
      {
        test: /\.(png|jpg|jpeg|gif|svg|woff|woff2)$/,
        loader: 'url-loader',
        query: {
          name: isDebug ? '[path][name].[ext]?[hash]' : '[hash].[ext]',
          limit: 10000,
        },
      },
      {
        test: /\.(eot|ttf|wav|mp3)$/,
        loader: 'file-loader',
        query: {
          name: isDebug ? '[path][name].[ext]?[hash]' : '[hash].[ext]',
        },
      },
    ],
  },

  resolve: {
    root: path.resolve(__dirname, '../src'),
    modulesDirectories: ['node_modules'],
    extensions: ['', '.webpack.js', '.web.js', '.js', '.jsx', '.json'],
  },

  cache: isDebug,
  debug: isDebug,

  stats: {
    colors: true,
    reasons: isDebug,
    hash: isVerbose,
    version: isVerbose,
    timings: true,
    chunks: isVerbose,
    chunkModules: isVerbose,
    cached: isVerbose,
    cachedAssets: isVerbose,
  },

  // The list of plugins for PostCSS
  // https://github.com/postcss/postcss
  postcss(bundler) {
    return {
      default: [
        // Transfer @import rule by inlining content, e.g. @import 'normalize.css'
        // https://github.com/jonathantneal/postcss-partial-import
        require('postcss-partial-import')({ addDependencyTo: bundler }),
        // Allow you to fix url() according to postcss to and/or from options
        // https://github.com/postcss/postcss-url
        require('postcss-url')(),
        // W3C variables, e.g. :root { --color: red; } div { background: var(--color); }
        // https://github.com/postcss/postcss-custom-properties
        require('postcss-custom-properties')(),
        // W3C CSS Custom Media Queries, e.g. @custom-media --small-viewport (max-width: 30em);
        // https://github.com/postcss/postcss-custom-media
        require('postcss-custom-media')(),
        // CSS4 Media Queries, e.g. @media screen and (width >= 500px) and (width <= 1200px) { }
        // https://github.com/postcss/postcss-media-minmax
        require('postcss-media-minmax')(),
        // W3C CSS Custom Selectors, e.g. @custom-selector :--heading h1, h2, h3, h4, h5, h6;
        // https://github.com/postcss/postcss-custom-selectors
        require('postcss-custom-selectors')(),
        // W3C calc() function, e.g. div { height: calc(100px - 2em); }
        // https://github.com/postcss/postcss-calc
        require('postcss-calc')(),
        // Allows you to nest one style rule inside another
        // https://github.com/jonathantneal/postcss-nesting
        require('postcss-nesting')(),
        // Unwraps nested rules like how Sass does it
        // https://github.com/postcss/postcss-nested
        require('postcss-nested')(),
        // W3C color() function, e.g. div { background: color(red alpha(90%)); }
        // https://github.com/postcss/postcss-color-function
        require('postcss-color-function')(),
        // Convert CSS shorthand filters to SVG equivalent, e.g. .blur { filter: blur(4px); }
        // https://github.com/iamvdo/pleeease-filters
        require('pleeease-filters')(),
        // Generate pixel fallback for "rem" units, e.g. div { margin: 2.5rem 2px 3em 100%; }
        // https://github.com/robwierzbowski/node-pixrem
        require('pixrem')(),
        // W3C CSS Level4 :matches() pseudo class, e.g. p:matches(:first-child, .special) { }
        // https://github.com/postcss/postcss-selector-matches
        require('postcss-selector-matches')(),
        // Transforms :not() W3C CSS Level 4 pseudo class to :not() CSS Level 3 selectors
        // https://github.com/postcss/postcss-selector-not
        require('postcss-selector-not')(),
        // Postcss flexbox bug fixer
        // https://github.com/luisrudge/postcss-flexbugs-fixes
        require('postcss-flexbugs-fixes')(),
        // Add vendor prefixes to CSS rules using values from caniuse.com
        // https://github.com/postcss/autoprefixer
        require('autoprefixer')(),
      ],
      sass: [
        require('autoprefixer')(),
      ],
    };
  },
};

//
// Configuration for the client-side bundle (client.js)
// -----------------------------------------------------------------------------

const clientConfig = extend(true, {}, config, {
  entry: './client.js',

  output: {
    filename: isDebug ? '[name].js?[chunkhash]' : '[name].[chunkhash].js',
    chunkFilename: isDebug ? '[name].[id].js?[chunkhash]' : '[name].[id].[chunkhash].js',
  },

  target: 'web',

  plugins: [

    // Define free variables
    // https://webpack.github.io/docs/list-of-plugins.html#defineplugin
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': isDebug ? '"development"' : '"production"',
      'process.env.BROWSER': true,
      __DEV__: isDebug,
    }),

    // Emit a file with assets paths
    // https://github.com/sporto/assets-webpack-plugin#options
    new AssetsPlugin({
      path: path.resolve(__dirname, '../build'),
      filename: 'assets.js',
      processOutput: x => `module.exports = ${JSON.stringify(x)};`,
    }),

    // Assign the module and chunk ids by occurrence count
    // Consistent ordering of modules required if using any hashing ([hash] or [chunkhash])
    // https://webpack.github.io/docs/list-of-plugins.html#occurrenceorderplugin
    new webpack.optimize.OccurrenceOrderPlugin(true),

    ...isDebug ? [] : [
      // Search for equal or similar files and deduplicate them in the output
      // https://webpack.github.io/docs/list-of-plugins.html#dedupeplugin
      new webpack.optimize.DedupePlugin(),

      // Minimize all JavaScript output of chunks
      // https://github.com/mishoo/UglifyJS2#compressor-options
      new webpack.optimize.UglifyJsPlugin({
        compress: {
          screw_ie8: true,
          warnings: isVerbose,
          unused: true
        },
      }),
    ],
  ],

  // Choose a developer tool to enhance debugging
  // http://webpack.github.io/docs/configuration.html#devtool
  devtool: isDebug ? 'source-map' : false,
});

//
// Configuration for the server-side bundle (server.js)
// -----------------------------------------------------------------------------

const serverConfig = extend(true, {}, config, {
  entry: './server.js',

  output: {
    filename: '../../server.js',
    libraryTarget: 'commonjs2',
  },

  target: 'node',

  externals: [
    /^\.\/assets$/,
    (context, request, callback) => {
      const isExternal =
        request.match(/^[@a-z][a-z/.\-0-9]*$/i) &&
        !request.match(/\.(css|less|scss|sss)$/i);
      callback(null, Boolean(isExternal));
    },
  ],

  plugins: [
    // Define free variables
    // https://webpack.github.io/docs/list-of-plugins.html#defineplugin
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': isDebug ? '"development"' : '"production"',
      'process.env.BROWSER': false,
      __DEV__: isDebug,
    }),

    // Adds a banner to the top of each generated chunk
    // https://webpack.github.io/docs/list-of-plugins.html#bannerplugin
    new webpack.BannerPlugin('require("source-map-support").install();',
      { raw: true, entryOnly: false }),

    // Do not create separate chunks of the server bundle
    // https://webpack.github.io/docs/list-of-plugins.html#limitchunkcountplugin
    new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 1 }),
  ],

  node: {
    console: false,
    global: false,
    process: false,
    Buffer: false,
    __filename: false,
    __dirname: false,
  },

  devtool: 'source-map',
});

export default [clientConfig, serverConfig];

P.S. Not sure if I should be filing this issue with you guys or react-calendar
Thanks!

question

Most helpful comment

Similar Unexpected token . on ".react-calendar" issue with next.js. It's set up to take CSS using @zeit/next-css which worked for Ant Design components. Used @allpwrfulroot steps noted earlier works as temporary workaround:

  1. use no-style version:
    import DatePicker from 'react-date-picker/dist/entry.nostyle';
  2. In the component, manually import the css Styles:
    import '../../node_modules/react-date-picker/dist/DatePicker.css';
    import '../../node_modules/react-calendar/dist/Calendar.css';

All 14 comments

@brian-kilpatrick, we had this same issue as well. I think this is a test configuration issue rather than an issue with react-date-picker.
Assuming you're using jest since you're project is based on react-starter-kit.
https://facebook.github.io/jest/docs/en/webpack.html
Mocking (s?css|less) files resolved this issue for us.

Same issue here.
react: ^16.2.0
(jest: ^17.0.0)

If that's the issue with running Jest, then mocking style files should help:

    "moduleNameMapper": {
      "\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
    },

where styleMock is simply:

module.exports = {};

This isn’t a test issue for me. Happening in prod

On May 12, 2018, at 3:45 AM, Wojciech Maj notifications@github.com wrote:

If that's the issue with running Jest, then mocking style files should help:

"moduleNameMapper": {
  "\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
},

where styleMock is simply:

module.exports = {};
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub, or mute the thread.

We have the exact same issue here.

When installing the package for the first time we are able to compile and run.
When stopping and starting our build process we get the unexpected token issue.

Looking into this, it seems that our compiler thinks that the css page Calendar.css is actually a javascript file.
I am not sure why this happens. For the time being we do the following to avoid the issue.
require.extensions['.css'] = () => { return; };
Placing the above directly under require('babel-register') fixes the issue for us.

I don't know why this fixes our issue, if anyone has experience with babel and webpack and can shine some light on this that would be great.
relevant link: https://github.com/webpack/webpack/issues/1754

Also seeing this in Meteor. Not using webpack.

Same. Using NextJS with next-css, and everything else has been working well. Commenting out both require('./files.css'); lines in node_modules/react-date-picker/dist/entry.js lets the page build, and importing the DatePicker and Calendar.css files manually gives the desired date-picking result?

+1

If you really don't want to setup your bundler to understand CSS files, then you need to import react-date-picker/dist/entry.nostyle instead, but mind you, you'll have to import this CSS anyway somehow to make the picker look right.

Hi,
I'm also facing the same issue. what's the solution?. My webpack config has the rules to load css files. Still facing the issue

@andy14312 , if your Webpack config properly matches CSS files this shouldn't be the case. Would you share your configuration?

@andy14312 , if your Webpack config properly matches CSS files this shouldn't be the case. Would you share your configuration?

here's the config

//global.Promise = require('bluebird'); // for node 0.10

const path                 = require('path'),
    webpack           = require('webpack'),
    ExtractTextPlugin = require("extract-text-webpack-plugin"),
    AssetsPlugin      = require('assets-webpack-plugin'),
    OfflinePlugin = require('offline-plugin'),
    LodashModuleReplacementPlugin = require('lodash-webpack-plugin'),
    ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin'),
    CleanWebpackPlugin = require('clean-webpack-plugin'),
    MomentLocalesPlugin = require('moment-locales-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const  { getFilePaths } = require('./scripts/webpack/filePaths');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const HappyPack = require('happypack');
const CompressionPlugin = require('compression-webpack-plugin');
const BrotliPlugin = require('brotli-webpack-plugin');

const buildPaths = getFilePaths(process.env.NODE_ENV);

const plugins = [
    new LodashModuleReplacementPlugin,
    new MomentLocalesPlugin(),
    new webpack.DefinePlugin({
        "process.env": {
            BROWSER: JSON.stringify(true),
            NODE_ENV: JSON.stringify( process.env.NODE_ENV || 'development' )
        }
    }),
    new ExtractTextPlugin(`${buildPaths.fileName}.css?v=[contenthash:8]`),
    new HappyPack({
        id: 'js',
        threads: 4,
        // https://github.com/babel/babel-loader#options
        loaders: ['babel-loader?cacheDirectory'],
    }),
    new AssetsPlugin({path: path.join(__dirname, 'etc')}),
    new webpack.optimize.CommonsChunkPlugin({names: ['common', 'vendor'], filename: `${buildPaths.fileName}.js?v=[hash:8]`}),
        /*new OfflinePlugin({
         publicPath : '/',
         safeToUseOptionalCaches: true,
         updateStrategy: 'changed',
         caches: 'all',
         externals: [
             '/',
             '/public/static/manifest.json',
             '/public/static/logo.png'
         ],
         ServiceWorker: {
         events: true,
             output: '../../../../sw.js',
             publicPath: '/sw.js'
         }
     })*/

];

if (process.env.NODE_ENV === 'analyse') {
    plugins.push(new BundleAnalyzerPlugin());
}

if(String(process.env.NODE_ENV)  !== 'undefined' && process.env.NODE_ENV !== 'local-dev') {
    plugins.push(new CleanWebpackPlugin([buildPaths.cleanBuild]));
    plugins.push(new webpack.optimize.ModuleConcatenationPlugin());
    plugins.push(new UglifyJsPlugin({
        uglifyOptions :{
            compress: {
                conditionals : false, //quill production build crashes
            },
            output: {
                comments: false,
            },
            exclude: [/\.min\.js$/gi] // skip pre-minified libs
        }
    }));
    plugins.push(new CompressionPlugin({
        asset: '[path].gz[query]',
        algorithm: 'gzip',
        test: /\.js$|\.css$|\.html$/,
        threshold: 10240,
        minRatio: 0.8
     }));
     plugins.push(new BrotliPlugin({
        asset: '[path].br[query]',
        test: /\.js$|\.css$|\.html$/,
        threshold: 10240,
        minRatio: 0.8
     }))
}

module.exports = {
    devServer : {
        headers: {
            'Access-Control-Allow-Origin': '*',
        },
    },
    target: 'web',
    entry: {
        vendor: [
            'react',
            'react-dom',
            'react-redux',
            'react-router',
            'redux-thunk',
            'react-redux-modal'
        ],
        common: [
            'core-js',
            'lodash',
            'axios',
            'jed'
        ],
        main: './client/app.js',
    },
    plugins,
    output: {
        path: path.join(__dirname, buildPaths.buildPath),
        publicPath: buildPaths.outPutPath,
        filename: `${buildPaths.fileName}.js?v=[chunkhash:8]`,
        chunkFilename: `${buildPaths.fileName}.js?v=[chunkhash:8]`,
        crossOriginLoading: "anonymous"
    },
    stats: {
        chunks: true
    },
    resolve: {
        modules: ['node_modules', 'public', 'shared', 'client'],
        extensions: ['*', '.js', ',jsx', '.json'],
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: 'css-loader!autoprefixer-loader'
                })
            },
            {
                test: /\.less$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: 'css-loader!autoprefixer-loader!less-loader'
                })
            },
            { test: /\.gif$/, use: "url-loader?limit=10000&mimetype=image/gif" },
            { test: /\.jpg$/, use: "url-loader?limit=10000&mimetype=image/jpg" },
            { test: /\.jpeg$/, use: "url-loader?limit=10000&mimetype=image/jpeg" },
            { test: /\.png$/, use: "url-loader?limit=10000&mimetype=image/png" },
            { test: /\.svg/, use: "url-loader?limit=26000&mimetype=image/svg+xml" },
            { test: /\.(woff|woff2|ttf|eot)/, use: `url-loader?limit=10000&name=${buildPaths.iconFontName}.[ext]?v=[hash:8]` },
            { test: /\.(jsx|js)$/, use: "babel-loader", exclude: [/node_modules/, /public/]},
            { test: /\.json$/, use: "json-loader"},
            { test: /\.txt$/, use: "raw-loader"},
            /*{
             test: /\.js$/,
             use: 'eslint',
             enforce:'pre',
             exclude: /node_modules|\.spec\.js/,
             options: {
             quiet: false,
             fix:false,
             failOnError: false,
             failOnWarning: false,
             emitError: false,
             emitWarning: false
             }
             }*/
        ]
    }
};

Similar Unexpected token . on ".react-calendar" issue with next.js. It's set up to take CSS using @zeit/next-css which worked for Ant Design components. Used @allpwrfulroot steps noted earlier works as temporary workaround:

  1. use no-style version:
    import DatePicker from 'react-date-picker/dist/entry.nostyle';
  2. In the component, manually import the css Styles:
    import '../../node_modules/react-date-picker/dist/DatePicker.css';
    import '../../node_modules/react-calendar/dist/Calendar.css';

I have same problem,
I'm use this boilerplate for ssr https://github.com/Brigad/ssr-starter-pack
when use entry.nostlye it's not work because its get styles from react semantic ui
could you show how to configure the webpack config, I don't understand webpack well. thanks

Was this page helpful?
0 / 5 - 0 ratings

Related issues

baffleinc picture baffleinc  Â·  4Comments

podlesny picture podlesny  Â·  7Comments

bhldev picture bhldev  Â·  6Comments

vanmanh49 picture vanmanh49  Â·  4Comments

jameskraus picture jameskraus  Â·  4Comments