webpack开环环境启动项目没有引入对应的js文件

之前按当前的webpack配置,npm run dev ,项目会在本地服务器运行,不知道改动了什么地方,现在项目运行起来之后,html页面没有压缩,也没有对应的引入js文件。
webpack.dev.js

const merge = require('webpack-merge');
const webpack = require("webpack");
const path = require('path');
const common = require('./webpack.common.js');

module.exports = merge(common, {
    output: { // 出口文件
        path: __dirname + '/dist',
        publicPath: '/',
        filename: '[name]/[name].js' //输出文件
    },
    devtool: 'inline-source-map',
    watch: true,
    devServer: {
        contentBase: path.join(__dirname, "./views"),
        inline:true,
        host: "0.0.0.0",
        port: "8081",
        overlay: true,
        open: true,
        hot: true,
        watchOptions: {
            poll: true,
        }
    },
    plugins: [
        // new HtmlWebpackInlineSourcePlugin(),
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NamedModulesPlugin(),
    ],
});

webpack.prod.js

const merge = require('webpack-merge');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const common = require('./webpack.common.js');
const path = require('path')
const BUILD_PATH = path.resolve(__dirname,'dist')  //  打包模板生成路径

module.exports = merge(common, {
    output: { // 出口文件
        path: BUILD_PATH,
        publicPath: './',
        filename: '[name]/[name].js' //输出文件
    },
    devtool: 'source-map',
    plugins: [
        new CleanWebpackPlugin(['dist']),
        new UglifyJSPlugin({
            sourceMap: true
        })
    ]
});

webpack.common.js

/**
 * Created by MBJ20180827S1 on 2018/10/19.
 */
const webpack = require("webpack");
const path = require('path');
const glob = require('glob');
const HtmlWebpackPlugin = require('html-webpack-plugin'); // html引擎
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackInlineSourcePlugin = require('html-webpack-inline-source-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');

function buildEntriesAndHTML() {
    // 用来构建entry
    const result = glob.sync('views/**/*.js');
    const config = {
        hash: false,
        inject: true
    };
    const entries = {};
    const htmls = [];
    result.forEach(item => {
        const one = path.parse(item);
        const outputfile = one.dir.split('/').slice(-1)[0];
        entries[outputfile] = './' + item;
        htmls.push(
            new HtmlWebpackPlugin({
                ...config,
                template: './' + one.dir + '/index.html',
                filename: './' + outputfile + '/'+outputfile+'.html', // 输出html文件的路径
                title:outputfile+'模版',
                chunks: [outputfile]
            })
        );
    });
    if (htmls.length > 0) {
        htmls.push(new HtmlWebpackInlineSourcePlugin());
    }
    return {
        entries,
        htmls
    };
}
const final = buildEntriesAndHTML();
console.log("final")
console.log(final.entries)
console.log(final.htmls)
module.exports = {
    entry: final.entries,
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                    {loader: 'postcss-loader', options: {plugins: [require("autoprefixer")("last 100 versions")]}}
                ]
            },
            {
                test: /\.less$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader?importLoaders=1',
                    {loader: 'postcss-loader', options: {plugins: [require("autoprefixer")("last 100 versions")]}},
                    'less-loader'
                ]
            },
            {
                test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
                /*use:[
                 {
                 loader: 'url-loader',
                 options: {
                 limit: 1024 * 10,
                 name: 'image/[name].[ext]',
                 fallback: 'file-loader'
                 }
                 },
                 {
                 loader: 'image-webpack-loader',// 压缩图片
                 options: {
                 bypassOnDebug: true,
                 }
                 }
                 ]*/
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            // name: './'+outputfile+'/static/assets/[name].[ext]',
                            name: 'static/assets/[name].[ext]',
                        }
                    },
                    {
                        loader: 'image-webpack-loader',// 压缩图片
                        options: {
                            bypassOnDebug: true,
                        }
                    }
                ]
            },
            {
                test: /\.(mp4|webm|ogg|mp3|wav|flac|aac|swf|mov)(\?.*)?$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: 'media/[name].[hash:7].[ext]',
                        }
                    },
                ]
            },
            {
                test: /\.js$/,
                exclude: [
                    /node_modules/,
                    path.resolve(__dirname, "assets/javascripts/swiper.min.js"),
                ],
                use: {
                    loader: "babel-loader"
                }
            },
            {
                test: /\.html$/,
                use: [
                    {
                        loader: "html-loader",
                        options: {minimize: true} // 加载器切换到优化模式,启用压缩。
                    }
                ]
            }
        ]
    },
    plugins: [
        new OptimizeCSSAssetsPlugin({
            assetNameRegExp: /\.css\.*(?!.*map)/g,  //注意不要写成 /\.css$/g
            cssProcessor: require('cssnano'),
            cssProcessorOptions: {
                discardComments: {removeAll: true},
                // 避免 cssnano 重新计算 z-index
                safe: true,
                // cssnano 集成了autoprefixer的功能
                // 会使用到autoprefixer进行无关前缀的清理
                // 关闭autoprefixer功能
                // 使用postcss的autoprefixer功能
                autoprefixer: false
            },
            canPrint: true
        }),
        new MiniCssExtractPlugin({
            filename: '[name]/[name].css',
            chunkFilename: '[name].css'
        }),
        ...final.htmls
    ],
    resolve: {
        extensions: ['.js', '.json', '.jsx', '.css']
    },
}

打包后生成的项目目录如下,假设文件夹名称为aaa或bbb,这是多页面的配置:

dist/
   aaa/
       aaa.html
       aaa.css
       aaa.js
   bbb/
       bbb.html
       bbb.css
       bbb.js
   static/
       assets/
           icon.jpg
           logo.png

这是npm run dev 跑起来的项目代码

clipboard.png

求webpack大神帮忙看看 哪里出问题了 ,很着急,万分感谢!

通过排查,找到了问题所在,是由于webpack.common.js中htmlwebpackplugin插件中,filename生成的文件名称默认应该是index.html,但是我改成我期望的名称之后,本地开发环境就不能识别了,如果改成index.html就是可以的,希望有大神可以帮忙解释下这是什么原理呢?

阅读 3.3k
2 个回答

filename: '[name]/[name].js' 这个与你写的模板内title冲突了。导致本地无法识别如何编译。详情请参考github-html-webpack-plugin

新手上路,请多包涵

应该是devServer里面有index字段,它的默认值是index.html,如果将htmlwebpackplugin里面的filename改成自己想要的,那么index也应该改成相应的filename.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题