使用webpack打包报错:Uncaught SyntaxError: Unexpected token <

如题

Uncaught SyntaxError: Unexpected token <

Uncaught SyntaxError: Unexpected token <

Uncaught SyntaxError: Unexpected token <

webpack配置如下:
base.js

const webpack = require("webpack");
const { resolve, join } = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin"); //主要有两个作用:1、将打包后html文件引入script、link;2、创建一个模板页的html入口文件
const CopyWebpackPlugin = require("copy-webpack-plugin"); // 在webpack中拷贝文件和文件夹
const ExtractTextPlugin = require("extract-text-webpack-plugin");

const CLIENT_FOLDER = resolve(__dirname, "./../");
const SERVER_FOLDER = resolve(__dirname, "./../server");
const nodeModulesPath = resolve(__dirname, "./../node_modules");

let config = {
    devtool: "#cheap-module-eval-source-map", //默认模式,便于从打包后的文件中找到子文件
    entry: {
        "modules/admin": [
            "babel-polyfill",
            CLIENT_FOLDER + "/src/modules/admin/app"
        ],
        "modules/front": [
            "babel-polyfill",
            CLIENT_FOLDER + "/src/modules/front/entry-client"
        ]
    },
    output: { //这里的输入好像被覆盖了,等等回来看
        path: CLIENT_FOLDER + "/dist",
        filename: "[name].ymc.js",
        publicPath: "/"
    },
    externals: { //将编辑器模块排除
        simplemde: "SimpleMDE"
    },
    plugins: [],
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: "vue-loader",
                options: {
                    loaders: {
                        less: [
                            "vue-style-loader",
                            "css-loader?minimize",
                            "less-loader"
                        ],
                        css: ["vue-style-loader", "css-loader?minimize"]
                    },
                    preserveWhitespace: false,//默认true,设置为 false,模版中 HTML 标签之间的空格将会被忽略
                    postcss: [
                        require("autoprefixer")({
                            browsers: ["last 7 versions"]
                        })
                    ]
                }
            },
            {
                test: /\.js[x]?$/,
                loader: "babel-loader",
                exclude: nodeModulesPath,
                query: {
                    presets: ['es2015']
                }
            },
            {
                test: /\.less$/,
                use: ["style-loader", "css-loader?minimize", "less-loader"]
            },
            {
                test: /\.css$/,
                use: ["style-loader", "css-loader?minimize"]
            },
            {
                //对图片路径进行处理,超过小于10000转base64
                test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
                loader: "url-loader",
                options: {
                    limit: 10000,
                    name: "img/[name].[hash:7].[ext]"
                }
            },
            {
                test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
                loader: "url-loader",
                options: {
                    limit: 10000,
                    name: "fonts/[name].[hash:7].[ext]"
                }
            }
        ]
    },
    resolve: {
        extensions: [".js", ".vue", ".json"],
        modules: [nodeModulesPath],
        alias: {//设置别名,简化路径!
            vue$: "vue/dist/vue.esm.js",
            vuex$: "vuex/dist/vuex.esm.js",
            "vue-router$": "vue-router/dist/vue-router.esm.js",
            simplemde$: "simplemde/dist/simplemde.min.js",
            "highlight.js$": "highlight.js/lib/highlight.js",
            fastclick: "fastclick/lib/fastclick.js",

        }
    },
    cache: true,//默认值,缓存webpack配置,提高打包速度
};

module.exports = config;

pro.js

const webpack = require("webpack");
const merge = require("webpack-merge"); //合并webpack配置
const { resolve, join } = require("path");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin"); //设置Html模板文件的引入和配置
const ExtractTextPlugin = require("extract-text-webpack-plugin"); //将css文件从js中单独抽离出来

const base = require("./webpack.base.config"); //基础webpack配置文件
const CLIENT_FOLDER = resolve(__dirname, "./../");
const SERVER_FOLDER = resolve(__dirname, "./../server");
const nodeModulesPath = resolve(__dirname, "./../node_modules");

const productionEnv = process.env.NODE_ENV === "production" ? true : false;

let config = merge(base, {
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        // 开启全局的模块热替换(HMR)

        new webpack.NamedModulesPlugin(),
        // 当模块热替换(HMR)时在浏览器控制台输出对用户更友好的模块名字信息,
        // 使模块呈现相对路径显示

        new HtmlWebpackPlugin({
            filename: "admin.html",
            template: CLIENT_FOLDER + "/src/modules/admin/index.html",
            inject: "body",//js文件防止的位置,默认true,参数:true、body、head、false
            chunks: productionEnv
                ? [
                      "modules/manifest_admin",
                      "modules/vendor_admin",
                      "modules/admin"
                  ]
                : ["modules/admin"],
            minify: {
                // 压缩的方式;分别是移除注解、合并文档中的空白、删除可删除的引号
                removeComments: true,
                collapseWhitespace: true,
                removeAttributeQuotes: true,
            }
            //chunksSortMode: 'dependency'//chunks的插入顺序
        }),

        new HtmlWebpackPlugin({
            filename: "front.html",
            template: CLIENT_FOLDER + "/src/modules/front/index.html",
            inject: 'body',
            chunks: productionEnv
                ? [
                      "modules/manifest_front",
                      "modules/vendor_front",
                      "modules/front"
                  ]
                : ["modules/front"],
            minify: {
                // 压缩的方式
                // removeComments: false,
                collapseWhitespace: true,
                removeAttributeQuotes: true,
            }
            //chunksSortMode: 'dependency'//决定了 script 标签的引用顺序;默认有四个选项,'none', 'auto',
        }),
        // 配置提取出的样式文件
        new ExtractTextPlugin("css/[name].[contenthash].css"),//contenthash是extraTextPlugin插件避免引用其css的文件改动,css文件也被重新构建,就是说不改动css,content文件是不会变的

        new webpack.DefinePlugin({//创建编译时的全局常量
            "process.env.NODE_ENV": JSON.stringify(
                process.env.NODE_ENV || "development"
            ),
            "process.env.VUE_ENV": '"client"'
        })
    ]
});
config.entry["modules/admin"].unshift(
    "event-source-polyfill",
    "webpack-hot-middleware/client?reload=true"
);
config.entry["modules/front"].unshift(
    "event-source-polyfill",
    "webpack-hot-middleware/client?reload=true"
);

if (process.env.NODE_ENV === "production") {
    // 删除devtool
    delete config.devtool;
    // 删除webpack-hot-middleware
    config.entry["modules/admin"].splice(0, 2);
    config.entry["modules/front"].splice(0, 2);
    config.output.filename = "[name].[chunkhash:8].min.js";//重置输出目录
    // 提取css
    config.module.rules[0].options.loaders = {
        less:ExtractTextPlugin.extract({
            use: [
                {
                    loader: "css-loader",
                    options: {
                        minimize: true,
                        sourceMap: true
                    }
                },
                {
                    loader: "less-loader",
                    options: {
                    }
                }
            ],
            fallback: "vue-style-loader"
        }),
        css: ExtractTextPlugin.extract({
            use: [
                {
                    loader: "css-loader",
                    options: {
                        minimize: true,
                        sourceMap: true
                    }
                }
            ],
            fallback: "vue-style-loader"
        })
    };
    // 删除HotModuleReplacementPlugin和NamedModulesPlugin
    config.plugins.shift();
    config.plugins.shift();
    config.plugins = config.plugins.concat([
        new webpack.optimize.UglifyJsPlugin({
            // 最紧凑的输出
            beautify: false,
            // 删除所有的注释
            comments: false,
            compress: {
                // 在UglifyJs删除没有用到的代码时不输出警告
                warnings: false,
                // 删除所有的 `console` 语句
                // 还可以兼容ie浏览器
                drop_console: true,
                // 内嵌定义了但是只用到一次的变量
                collapse_vars: true,
                // 提取出出现多次但是没有定义成变量去引用的静态值
                reduce_vars: true
            }
        }),
        // 分别提取vendor、manifest
        new webpack.optimize.CommonsChunkPlugin({
            name: "modules/vendor_admin",
            chunks: ["modules/admin"],
            minChunks: function(module, count) {
                return (
                    module.resource &&
                    /\.js$/.test(module.resource) &&
                    module.resource.indexOf(nodeModulesPath) === 0
                );
            }
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: "modules/manifest_admin",
            chunks: ["modules/vendor_admin"]
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: "modules/vendor_front",
            chunks: ["modules/front"],
            minChunks: function(module, count) {
                return (
                    module.resource &&
                    /\.js$/.test(module.resource) &&
                    module.resource.indexOf(nodeModulesPath) === 0
                );
            }
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: "modules/manifest_front",
            chunks: ["modules/vendor_front"]
        }),
        // copy static
        // new CopyWebpackPlugin([
        //     {
        //         from: CLIENT_FOLDER + "/static",
        //         to: CLIENT_FOLDER + "/dist/static",
        //         ignore: [".*"]
        //     }
        // ])
    ]);
}
// console.log(config);
module.exports = config;
阅读 16k
3 个回答

看这个错误信息很像是你的代码里有 ES6 的箭头函数,但没有使用 babel 进行编译

这个是代码上的语法错误。大与号不识别,这个有可能是楼上说的,你用es6语法的箭头函数,在编译时没有转译成es5的语法。活着就是代码上多写了个大于号。感觉第一个可能性大,你可以百度查下,怎么6转5

新手上路,请多包涵

参考https://github.com/jantimon/h...,原因是babel-loader检查了node_modules中的模板文件。解决方法:

// ...
rules: [{ test: /.js$/, use: "babel-loader", exclude: /node_modules/ }]
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题