1

When trying to run webpack into my JS folder, I'm getting this error

$ node_modules/.bin/webpack --config webpack.js 
/Users/xxx/Documents/js/webpack.js:1
(function (exports, require, module, __filename, __dirname) { import config from './'
                                                          ^^^^^^
SyntaxError: Unexpected token import
at new Script (vm.js:51:7) ...

My .babelrc file contains:

{
  "presets": ["env"]
}

webpack.cofig.js main lines are:

import config from './'
import path from 'path'
import deepMergeWithArray from '../lib/deepMergeWithArray.js'
import webpack from 'webpack'
import WebpackNotifierPlugin from 'webpack-notifier'
import ProgressBarPlugin from 'progress-bar-webpack-plugin'

export default function() {
...
let __defaults = {
    debug: false,
    watch: false,
    devtool: false,
    context: devJS,
    entry: {},

    output: {
        filename: '[name].js',
        chunkFilename: chunks,
        path: distJS
    },
    module: {
        rules: [
            {
              test: /\.(js|jsx)$/,
              exclude: /(node_modules|bower_components)/,
              use: {
                loader: 'babel-loader',
                options: {  // << add options with presets env
                  presets: ['env']
                }
              }
            }
          ],
         ...
        ]
    },

    plugins: [
        new ProgressBarPlugin(),
        new WebpackNotifierPlugin(),
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.OccurrenceOrderPlugin(true),
        new webpack.ProvidePlugin(providePluginDefaults),

        new webpack.DefinePlugin({
            DEBUG: config.options.debug,
            STAGE: env === 'development' ? 'dev' : 'dist'
        }),

        new webpack.ResolverPlugin(
            new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
        )
    ]
}
__defaults.entry[filename] = './main.js'
__defaults.entry[vendor] = [
    'jquery',
    'lodash',
    'mediator-js',
    'fastclick',
    'skrollr',
    'is_js',
    'jquery-validation',
    'babel-polyfill'
]

if(env === 'development') {
    __defaults.devtool = 'source-map';
    __defaults.debug = true;
}

if(env === 'distribution') {
    __defaults.plugins.push(
        new webpack.optimize.CommonsChunkPlugin({
            name: vendor,
            minChunks: Infinity
        }),
        //new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 20 }),
        new webpack.optimize.MinChunkSizePlugin({minChunkSize: 10000}),
        new webpack.optimize.AggressiveMergingPlugin({
            minSizeReduce: 1.5,
            moveToParents: true
        }),
        new webpack.optimize.UglifyJsPlugin({
            sourceMap: false,
            compress: {
                warnings: false,
                sequences: true,
                dead_code: true,
                conditionals: true,
                booleans: true,
                unused: true,
                if_return: true,
                join_vars: true,
                drop_console: true
            },
            mangle: {
                except: ['$super', '$', 'exports', 'require']
            },
            output: {
                comments: false
            }
        })
    )
}

let __project = {

    resolve: {
        alias: {
            validate           : 'jquery-validation',
            'validate-methods' : 'jquery-validation/dist/additional-methods.js',
            'jquery-easing'    : 'jquery.easing/jquery.easing.min.js',
            datepicker         : 'jquery-ui/datepicker.js',
            tooltipster        : 'tooltipster/js/jquery.tooltipster.js',
            lazyloadxt         : 'lazyloadxt/dist/jquery.lazyloadxt.extra.js',
            modernizr          : 'modernizr/modernizr.js',
            'jquery-base'      : 'jquery/dist/jquery.js',
            'handlebars'       : require.resolve('handlebars/runtime')
        }
    },

    module: {
        noParse: [
            /[\\\/]i18next[\\\/]bin[\\\/]index\.js$/,
            /[\\\/]i18next-xhr-backend[\\\/]bin[\\\/]index\.js$/
        ],
        loaders: [
            {
                test: require.resolve("jquery"),
                loader: 'expose?jQuery'
            },
            {
                test: /(flickity|flickity-imagesloaded)/,
                loader: 'imports?define=>false&this=>window'
            },
            {
                test: /[\\\/]lazyloadxt[\\\/]dist[\\\/]jquery.lazyloadxt\.js$/,
                loader: 'exports?jQuery.fn.lazyLoadXT'
            },
            {
                test: /[\\\/]bower_components[\\\/]tooltipster[\\\/]js[\\\/]jquery.tooltipster\.js$/,
                loader: 'exports?jQuery.fn.tooltipster'
            },
            {
                test: /[\\\/]bower_components[\\\/]modernizr[\\\/]modernizr\.js$/,
                loader: "imports?this=>window!exports?window.Modernizr"
            },
            {
                test: /isotope\-|fizzy\-ui\-utils|desandro\-|masonry|outlayer|get\-size|doc\-ready|eventie|eventemitter/,
                loader: 'imports?define=>false&this=>window'
            },
            {
                test: /\.json$/,
                exclude: /node_modules/,
                loader: 'json-loader'
            }
        ]
    },

    plugins: [
        //new webpack.IgnorePlugin(/^\.\/locale$/, [/moment$/]),
        new webpack.ProvidePlugin(Object.assign(providePluginDefaults, {
            'moment'        : 'moment',
            i18n            : 'i18next',
            'window.i18n'   : 'i18next'
        }))
    ]
}

return deepMergeWithArray(__defaults, __project)

}

I'm completely newbie to these technologies. I just want to generate several minified JS files using that script and the source JS code, but I'm not able yet.

The versions I'm using are the next ones:

$ node -v
v9.10.1
$ npm -v
5.6.0
$ ./node_modules/.bin/webpack -v
4.5.0

Any help would be much appreciated.

nano
  • 2,511
  • 4
  • 25
  • 42
  • It's really hard to say. The error said that you're using `import` in the js file that doesn't support `import` keyword. Try remove everything and start step-by-step to debug. Don't write the code as an expert and say you're just a newbie –  Apr 14 '18 at 15:44
  • Hi @nano please take a look at this question on stack overflow. [Using ES6 in Babel Configuration](https://stackoverflow.com/questions/31903692/how-can-i-use-es6-in-webpack-config-js) – Mudasar Rauf Apr 14 '18 at 15:45
  • Remove all the plugins, alias.... and try again. For beginner, the configuration just needs "entry", "output", "module.rules" ^^! –  Apr 14 '18 at 15:47
  • Thanks for your comments. I've already said I'm newbie. I've just received all the source files (and the webpack config file) and need to compile them, in order to do some changes in the source files and generate the same minified JS files to upload to the dev website. – nano Apr 14 '18 at 15:48
  • @nano Don't copy-paste code and file in webpack. I'd tried it before. It doesn't work and hard to understand how it works. That's my experience ^^! –  Apr 14 '18 at 15:54
  • @BehindTheScene yeah, but that code was working on the original developer environment and that's exactly what I've received. should I work on recreating the webpack config file then? Not sure I'll be able to do that :S – nano Apr 14 '18 at 15:56
  • @nano Then, try to check everything **exactly**: _path_, _packages_, _package versions_. If some package was not installed, install them using "npm install package_name" (make sure that you have file "package.json" in the root of the project). –  Apr 14 '18 at 16:01

2 Answers2

0

Make sure you have babel-cli and babel-preset-env installed.

Rename your webpack.config.js to webpack.config.babel.js

Try running webpack again. npx webpack --config ./webpack.config.babel.js

jpdelatorre
  • 3,573
  • 1
  • 20
  • 25
  • Both dependencies were already installed. After running `npx webpack --config ./webpack.config.babel.js` I'm still getting `Unexpected token import` – nano Apr 14 '18 at 16:27
  • what's in your `import config from './'` and where is it? – jpdelatorre Apr 14 '18 at 16:33
0

Try updating your .babelrc code with this,

{
 "presets": [
    ["env", {"modules": false}],
    "stage-0",
    "react"
  ]
}