webpack插件配置(一) webpack-dev-server 路徑配置


本文的路徑配置主要涉及到webpack.config.js文件中devServer與output兩個選項的配置

 

webpack-dev-server定義

webpack-dev-server主要是啟動了一個使用expressHttp服務器。它的作用主要是用來伺服資源文件。此外這個Http服務器client使用了websocket通訊協議,原始文件作出改動后,webpack-dev-server會實時的編譯,但是最后的編譯的文件並沒有輸出到目標文件夾,即output中的配置:

 

    output: {
        path: './dist/js',
        filename: 'bundle.js'
    }

 

注意:你啟動webpack-dev-server后,你在目標文件夾中是看不到編譯后的文件的,實時編譯后的文件都保存到了內存當中。因此很多同學使用webpack-dev-server進行開發的時候都看不到編譯后的文件

 

配置實踐

前提:

1.項目的目錄結構如下:

    app
|__content
| |__index.html
|__src | |__index.js |__node_modules |__package.json |__webpack.config.js

2.package.json添加start命令,配置完成后運行npm start命令,打開瀏覽器訪問http://127.0.0.1:8080/
  "scripts": {
    "start": "webpack-dev-server"
  },

配置一:
webpack.config.js配置
    //應用程序的起點入口。這個起點開始,應用程序啟動執行
entry: './index.js', output: { filename: 'bundle.js', }, devServer: { inline: true, contentBase: './content', },

index.html內容:注意script src的值

<!doctype html public "storage">
<html>
<meta charset=utf-8/>
<title>My First React Router App</title>
<div id=app></div>
<script src="bundle.js"></script>

結論一:contentBase告訴服務器從哪個目錄提供內容,只有在加載靜態文件時才需要。上面index.html在項目的content文件夾下,所以contentBase值為'./content'。

 

配置二:

webpack.config.js

    entry: './index.js',

    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
        publicPath: '/asset/',
    },

    devServer: {
        inline: true,
        contentBase: './content',
    },

html配置

<!doctype html public "storage">
<html>
<meta charset=utf-8/>
<title>My First React Router App</title>
<div id=app></div>
<script src="asset/bundle.js"></script>

運行結果:項目根目錄沒有生成dist文件夾,瀏覽器中正常顯示‘Hello, React Router ’

結論二:output中的path是生成目標文件的絕對路徑,但是目標文件路徑中是看不到編譯后的文件,因為webpack-dev-server實時編譯的文件都保存到了內存中

結論三:output中的publicPath是訪問output生成的文件的路徑(是一個訪問路徑,不需要對應真實的文件路徑),所以在html中需要將src設置為'asset/bundle.js'

 

配置三:

webpack.config.js

    entry: './index.js',

    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
        publicPath: '/asset/',
    },

    devServer: {
        inline: true,
        contentBase: './content',
 publicPath: '/new/asset/',
    },

html配置

<!doctype html public "storage">
<html>
<meta charset=utf-8/>
<title>My First React Router App</title>
<div id=app></div>
<script src="new/asset/bundle.js"></script>

結論四:devServer中的publicPath配置會覆蓋output中的publicPath配置

 

文檔

官方說明

文章參考

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM