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

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

 

webpack-dev-server定義node

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

 

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

 

注意:你啓動webpack-dev-server後,你在目標文件夾中是看不到編譯後的文件的,實時編譯後的文件都保存到了內存當中。所以不少同窗使用webpack-dev-server進行開發的時候都看不到編譯後的文件web

 

配置實踐express

前提:npm

1.項目的目錄結構以下:json

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/
|__content
| |__index.html
index.js
  "scripts": {
    "start": "webpack-dev-server"
  },

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

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

<!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配置

 

文檔

官方說明

文章參考

相關文章
相關標籤/搜索