小編給大家分享一下vue-loader在項目中是怎樣配置的,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
創(chuàng)新互聯(lián)堅持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:成都網(wǎng)站建設(shè)、成都網(wǎng)站制作、企業(yè)官網(wǎng)、英文網(wǎng)站、手機端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時代的武平網(wǎng)站設(shè)計、移動媒體設(shè)計的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!
什么是vue-loader
這是我入職第三天的故事,在寫這篇文章之前,先來看看咱們今天要講的主角——vue-loader,你對它了解多少?

這是我今天的回答,確實,vue-loader是webpack的一個loader,用于處理.vue文件。
.vue 文件是一個自定義的文件類型,用類 HTML 語法描述一個 Vue 組件。每個 .vue 文件包含三種類型的頂級語言塊 <template>、<script>和 <style>。
vue-loader 會解析文件,提取每個語言塊,如有必要會通過其它 loader 處理(比如<script>默認(rèn)用babel-loader處理,<style>默認(rèn)用style-loader處理),最后將他們組裝成一個 CommonJS 模塊,module.exports 出一個 Vue.js 組件對象。
vue-loader 支持使用非默認(rèn)語言,比如 CSS 預(yù)處理器,預(yù)編譯的 HTML 模版語言,通過設(shè)置語言塊的 lang 屬性。例如,你可以像下面這樣使用 Sass 語法編寫樣式:
<style lang="sass"> /* write Sass! */ </style>
知道了什么是vue-loader之后,我們先來創(chuàng)建項目。為了快速地聊聊vue-loader,我在這里推薦用腳手架工具 @vue/cli 來創(chuàng)建一個使用 vue-loader 的項目:
npm install -g @vue/cli vue create hello-world cd hello-world npm run serve
這個過程我可以等等你們,because this might take a while...

當(dāng)你在瀏覽器里輸入localhost:8080之后,瀏覽器會友善地渲染出一個Welcome to Your Vue.js App的歡迎頁面。
緊接著,我們需要打開你擅長的編輯器,這里我選用的是VSCode,順手將項目導(dǎo)入進來,你會看到最原始的一個項目工程目錄,里面只有一些簡單的項目構(gòu)成,還沒有vue-loader的配置文件:

首先,我們需要在項目根目錄下面新建一個webpack.config.js文件,然后開始我們今天的主題。
手動配置css到單獨文件
說到提取css文件,我們應(yīng)該先去terminal終端去安裝一下相關(guān)的npm包:
npm install extract-text-webpack-plugin --save-dev
先來說個簡答的方法,上代碼:
// webpack.config.js
var ExtractTextPlugin = require("extract-text-webpack-plugin")
module.exports = {
// other options...
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
extractCSS: true
}
}
]
},
plugins: [
new ExtractTextPlugin("style.css")
]
}上述內(nèi)容將自動處理 *.vue 文件內(nèi)的 <style> 提取到style.css文件里面,并與大多數(shù)預(yù)處理器一樣開箱即用。
注意這只是提取 *.vue 文件 - 但在 JavaScript 中導(dǎo)入的 CSS 仍然需要單獨配置。
接下來我們再看看如何手動配置:
// webpack.config.js
var ExtractTextPlugin = require("extract-text-webpack-plugin")
module.exports = {
// other options...
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
css: ExtractTextPlugin.extract({
use: 'css-loader',
fallback: 'vue-style-loader' // 這是vue-loader的依賴
})
}
}
}
]
},
plugins: [
new ExtractTextPlugin("style.css")
]
}此舉便將所有 Vue 組件中的所有已處理的 CSS 提取到了單個的 CSS 文件。
如何構(gòu)建生產(chǎn)環(huán)境
生產(chǎn)環(huán)境打包,目的只有兩個:1.壓縮應(yīng)用代碼;2.去除Vue.js中的警告。
下面的配置僅供參考:
// webpack.config.js
module.exports = {
// ... other options
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin()
]
}當(dāng)然,如果我們不想在開發(fā)過程中使用這些配置,有兩種方法可以解決這個問題:
1.使用環(huán)境變量動態(tài)構(gòu)建;
例如:const isDev = process.env.NODE_ENV==='development'
或者:const isProd = process.env.NODE_ENV === 'production'
2.使用兩個分開的 webpack 配置文件,一個用于開發(fā)環(huán)境,一個用于生產(chǎn)環(huán)境。把可能共用的配置放到第三個文件中。
借鑒大牛的經(jīng)驗
這里提供一個網(wǎng)上標(biāo)準(zhǔn)的寫法,名字叫做vue-hackernews-2.0,這里是傳送門:https://github.com/vuejs/vue-hackernews-2.0
其中共用的配置文件webpack.base.config.js的代碼如下:
const path = require('path')
const webpack = require('webpack')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const { VueLoaderPlugin } = require('vue-loader')
const isProd = process.env.NODE_ENV === 'production'
module.exports = {
devtool: isProd
? false
: '#cheap-module-source-map',
output: {
path: path.resolve(__dirname, '../dist'),
publicPath: '/dist/',
filename: '[name].[chunkhash].js'
},
resolve: {
alias: {
'public': path.resolve(__dirname, '../public')
}
},
module: {
noParse: /es6-promise\.js$/, // avoid webpack shimming process
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
compilerOptions: {
preserveWhitespace: false
}
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'url-loader',
options: {
limit: 10000,
name: '[name].[ext]?[hash]'
}
},
{
test: /\.styl(us)?$/,
use: isProd
? ExtractTextPlugin.extract({
use: [
{
loader: 'css-loader',
options: { minimize: true }
},
'stylus-loader'
],
fallback: 'vue-style-loader'
})
: ['vue-style-loader', 'css-loader', 'stylus-loader']
},
]
},
performance: {
maxEntrypointSize: 300000,
hints: isProd ? 'warning' : false
},
plugins: isProd
? [
new VueLoaderPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false }
}),
new webpack.optimize.ModuleConcatenationPlugin(),
new ExtractTextPlugin({
filename: 'common.[chunkhash].css'
})
]
: [
new VueLoaderPlugin(),
new FriendlyErrorsPlugin()
]
}然后看看用于開發(fā)環(huán)境的webpack.client.config.js的配置是如何寫的:
const webpack = require('webpack')
const merge = require('webpack-merge')
const base = require('./webpack.base.config')
const SWPrecachePlugin = require('sw-precache-webpack-plugin')
const VueSSRClientPlugin = require('vue-server-renderer/client-plugin')
const config = merge(base, {
entry: {
app: './src/entry-client.js'
},
resolve: {
alias: {
'create-api': './create-api-client.js'
}
},
plugins: [
// strip dev-only code in Vue source
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
'process.env.VUE_ENV': '"client"'
}),
// extract vendor chunks for better caching
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: function (module) {
// a module is extracted into the vendor chunk if...
return (
// it's inside node_modules
/node_modules/.test(module.context) &&
// and not a CSS file (due to extract-text-webpack-plugin limitation)
!/\.css$/.test(module.request)
)
}
}),
// extract webpack runtime & manifest to avoid vendor chunk hash changing
// on every build.
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest'
}),
new VueSSRClientPlugin()
]
})
if (process.env.NODE_ENV === 'production') {
config.plugins.push(
// auto generate service worker
new SWPrecachePlugin({
cacheId: 'vue-hn',
filename: 'service-worker.js',
minify: true,
dontCacheBustUrlsMatching: /./,
staticFileGlobsIgnorePatterns: [/\.map$/, /\.json$/],
runtimeCaching: [
{
urlPattern: '/',
handler: 'networkFirst'
},
{
urlPattern: /\/(top|new|show|ask|jobs)/,
handler: 'networkFirst'
},
{
urlPattern: '/item/:id',
handler: 'networkFirst'
},
{
urlPattern: '/user/:id',
handler: 'networkFirst'
}
]
})
)
}
module.exports = config最后來看看開發(fā)環(huán)境中的webpack.server.config.js的配置是怎么寫的:
const webpack = require('webpack')
const merge = require('webpack-merge')
const base = require('./webpack.base.config')
const nodeExternals = require('webpack-node-externals')
const VueSSRServerPlugin = require('vue-server-renderer/server-plugin')
module.exports = merge(base, {
target: 'node',
devtool: '#source-map',
entry: './src/entry-server.js',
output: {
filename: 'server-bundle.js',
libraryTarget: 'commonjs2'
},
resolve: {
alias: {
'create-api': './create-api-server.js'
}
},
// https://webpack.js.org/configuration/externals/#externals
// https://github.com/liady/webpack-node-externals
externals: nodeExternals({
// do not externalize CSS files in case we need to import it from a dep
whitelist: /\.css$/
}),
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
'process.env.VUE_ENV': '"server"'
}),
new VueSSRServerPlugin()
]
})如何進行代碼檢驗
你可能有疑問,在 .vue 文件中你怎么檢驗?zāi)愕拇a,因為它不是 JavaScript。我們假設(shè)你使用 ESLint (如果你沒有使用話,你應(yīng)該去使用!)。
首先你要去安裝eslint-loader:
npm install eslint eslint-loader --save-dev
然后將它應(yīng)用在pre-loader上:
// webpack.config.js
module.exports = {
// ... other options
module: {
rules: [
{
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /node_modules/
}
]
}
}看完了這篇文章,相信你對“vue-loader在項目中是怎樣配置的”有了一定的了解,如果想了解更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!
新聞名稱:vue-loader在項目中是怎樣配置的
文章源于:http://chinadenli.net/article38/ppddpp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供外貿(mào)建站、關(guān)鍵詞優(yōu)化、做網(wǎng)站、靜態(tài)網(wǎng)站、建站公司、響應(yīng)式網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)