wlx200510 / webpack4.x-learn

学习webpack4.0的最新配置语法和新特性,分享给大家
177 stars 66 forks source link

关于打包后打开index.html的问题 #8

Closed LJJ1994 closed 5 years ago

LJJ1994 commented 5 years ago

大佬你好!我想请教个问题,就是我在您的代码基础上修改了js和css打包后的输出路径,那么我在执行打包命令 npm run build 后,打开打包目录dist下的index.html,浏览器提示

‘GET file:///C:/Users/Administrator/Desktop/webpack-list/webpack4.x/webpack4.x-learn/dist/css/static/images/webpack.cb00934.png net::ERR_FILE_NOT_FOUND’。

这里的背景图片请求失败,我查看了一下打包后的css的background路劲为: ‘background-image:url(static/images/webpack.cb00934.png)’。

dist的文件目录树为以下: --dist ------css ---------index.css ---------page.css ------js ---------common.js ---------index.js ---------page.js ------static ---------images -----------------webpack.cb0934.png ---------webpack.png -------index.html -------manifest.json -------page.html -------vendor.dll.js

修改代码如下:

//这是webpack.base.js output: { path: resolve('dist'), filename: 'js/[name].[hash].js' }, plugins: [ new HappyPack({ id: 'happy-babel-js', loaders: ['babel-loader?cacheDirectory=true'], threadPool: happyThreadPool }), new MiniCssExtractPlugin({ filename: "css/[name].css", chunkFilename: "css/[id].css" //修改此处 }), new ProgressBarPlugin({ format: ' build [:bar] ' + chalk.green.bold(':percent') + ' (:elapsed seconds)' }), ]

LJJ1994 commented 5 years ago

想知道是什么原因呢??

frontendGeek commented 5 years ago

我猜想你是想把css单独放到一个文件夹里面?这样只改文件输出路径,会导致里面资源的相对路径不正确,要解决这个问题,需要在另外的地方更改css的图片引用相对路径,解决方法如下:

{
    test: /\.css$/,
    use: ['css-hot-loader', 
             {
                  loader:MiniCssExtractPlugin.loader,
                  options: {
                       publicPath: '../'
                  }
             }, 
            'css-loader', 'postcss-loader'],
    include: [resolve('src')], //限制范围,提高打包速度
    exclude: /node_modules/
}
wlx200510 commented 5 years ago

解决方法跟frontendGeek说的一致,请试一下,不行的话再打开issue

LJJ1994 commented 5 years ago

解决了,确实是 @frontendGeek 说的问题。谢谢!