简体   繁体   中英

Webpack less-loader Missing Base Path on Production Build

I've got a vue-js app that uses webpack. Everything works fine in development and test environments, but I'm having trouble getting it to build for production.

I've got background images in the LESS files. The image files are in /static . (I'm not sure whether that's kosher or if they should be in side src/assets .)

At any rate, when the LESS has something like this:

 background-url: url("/static/img/foobar/my-image.svg") 

Then the compilted CSS will have the same url

 background-url: url("/static/img/foobar/my-image.svg") 

When the browser loaders, it can't find that imgate file. The browser is attempting to find the file here:

file:///static/img/foobar/my-image.svg

Can anyone recommend a way to prepend the absolute path when the app builds for production?

Do you have your static assets outside of our project directory in /static ? Otherwise I don't get why your browser is trying to request it from file:///static/img/foobar/my-image.svg

anyway, your static assets should be part of your repo/project. They do not need to be in src directory, a /static folder within the root of your project is just fine.

when you compile your application - let's say into a dist folder - you should copy the images also in that dist folder. In my app I use the copy-webpack-plugin for that task (I have my images in ./public/assets/img/.. and I reference them as /assets/img/.. )

    const CopyWebpackPlugin = require('copy-webpack-plugin');
    ...

    plugins: [
    ...
    /** copy all files from the public folder to the compilation root */
    new CopyWebpackPlugin([{
        from: 'public',
        to  : ''
    }]),
    ...

also you should make sure that you have the file-loader in place for your static assets. I use it like so:

  {
       test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)(\??\#?v=[.0-9]+)?$/,
       use : 'file-loader?name=assets/[name].[hash].[ext]'
  }

I hope this will help you to resolve your problem.

I ended up moving the images into assets/img and then updating my webpack config to specify the directory using publicPath . Here's what it ended up looking like:

      {
    test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
    loader: 'file-loader',
    include: [resolve('src')],
    options: {
      limit: 10000,
      name: '/[name].[hash:7].[ext]',
      publicPath: path.resolve(__dirname, 'app')
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM