2017-08-30 73 views
2

我有我的webpack.config像這樣:CSS加載器URL根不修改URL

module: { 
    rules: [ 
     { 
      test: /\.css$/, 
      use: ExtractTextPlugin.extract({ 
       fallback: 'style-loader', 
       use: { loader: 'css-loader', options: { url: false, root: 'http://localhost:9000/' } } 
      }), 
      exclude: /node_modules/ 
     } 
    ] 
}, 

css-loader options documentation它說:

如果根查詢參數設置,但是,這將是預先附加到URL然後翻譯。

如果我的CSS看起來像這樣:

select-page { 
    background-image: url('assets/background.png') !important; 
} 

我期望的輸出url'http://localhost/9000/assets/background.png'

但是,這不是我所得到的,當我運行構建時沒有改變。

回答

-1

嘗試更改webpack配置文件。並檢查資產文件夾應下提出的src文件夾

select-page { 
    background-image: url('assets/background.png') !important; 
} 

module: { 
    rules: [ 
      { 
       test: /\.css$/, 
       use: ['style-loader','css-loader'], 
      }, 
      { 
      test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/, 
      use: [ 
       { 
        loader: 'file-loader?name=assets/[name].[ext]', 
       } 
      ] 
      } 
     ] 
}, 
0

因此,爲了得到這個工作,我需要確保我設置{ url: true }或剛剛離開了那個關鍵,因爲它默認爲true。

但後來因爲我拉我的資產,通過我在CSS設置資產相對URLfile-loader他們感動:

.select-page { 
    background-image: url('/assets/background.png') !important; 
} 

這就帶來了一個新的問題,與{ url: true }這意味着css-loader是要試圖解決它 - 但它不能因爲不存在的文件有.....

所以我也必須使用{ alias: { } }像這樣:

{ 
    test: /\.css$/, 
    use: ExtractTextPlugin.extract({ 
     fallback: 'style-loader', 
     use: { 
      loader: 'css-loader', 
      options: { 
       root: 'http://localhost:8080/', 
       alias: { 
        './assets': path.resolve(__dirname, './resources/images') 
       } 
      } 
     } 
    }), 
    exclude: /node_modules/ 
} 

這意味着當css-loader嘗試解析url將換出/assetspath.resolve(__dirname, './resources/images')這實際上是在資源所在。但它不會影響原始url

還有就是爲什麼在alias關鍵是用./前綴,因爲它不只是一個/工作的原因,我認爲這是因爲css-loader總會preprend一個/.它繼續處理之前url

然後{ root: '' }被前置到它,所以我得到我想要的輸出:

.select-page { 
    background-image:url("http://localhost:8080/assets/background.png") 
} 

這似乎並不理想,我 - 也許這只是因爲我的工作流程略有不同!