zl程序教程

您现在的位置是:首页 >  前端

当前栏目

webpack搭建基础vue项目

2023-06-13 09:12:15 时间

新键目录

  • src
    • APP.vue
    • index.js

npm init -y

npm i vue vue-loader vue-template-compiler cross-env css-loader style-loader url-loader file-loader html-webpack-plugin webpack-dev-server

APP.vue

<template> 
 <div id="app"> 
      hello word  
 </div> 
</template> 
<script> 
export default { 
    data(){ 
 return { 
          title:'word hello' 
 } 
 } 
} 
</script> 
<style> 
</style> 

index.js

import Vue from 'vue' 
import App from './APP.vue' 
const root = document.createElement('div') 
document.body.appendChild(root) 
new Vue({ 
    render:(h)=>h(App) 
}).$mount(root)//渲染App内容 

package.json

... 
"scripts": { 
 "build": "cross-env NODE=production webpack --config webpack.config.js", 
 "dev": "cross-env NODE=production webpack-dev-server --config webpack.config.js" 
 }, 
 ... 

webpack.config.js

const path = require('path') 
const VueLoaderPlugin = require('vue-loader/lib/plugin') 
const HTMLPlugin = require('html-webpack-plugin') 
const webpack = require('webpack') 
//获取package.json cross 环境变量 
const isDev = process.env.NODE_ENV==='development' 
const config ={ 
    entry:'./src/index.js', 
    output:{ 
        filename:'bundle.js', 
        path:path.join(__dirname,'dist') 
 }, 
 module:{ 
        rules:[ 
 { 
                test:/\.vue$/, 
                loader:'vue-loader' 
 }, 
 { 
                test:/\.css$/, 
 use:['style-loader','css-loader'] 
 }, 
 { 
                test:/\.(png|jpg|jpeg|gif|svg)/, 
 use:[ 
 { 
                        loader:'url-loader', 
                        options:{ 
                            limit:1024, 
                            name:'[name].[ext]' 
 } 
 } 
 ] 
 } 
 ] 
 }, 
    plugins:[ 
 //配置环境变量 全局访问 
 new webpack.DefinePlugin({ 
 'process.env':{ 
                NODE_ENV:isDev?'"development"':'"production"' 
 } 
 }), 
 new VueLoaderPlugin(), 
 new HTMLPlugin() 
 ] 
} 
//开发模式生效 
if(isDev){ 
 //webpacserver  
    config.devServer={ 
        port:3000, 
        host:'0.0.0.0', 
        overlay:{ 
            errors:true 
 }, 
        hot:true 
 } 
 //热更新 
    config.plugins.push( 
 new webpack.HotModuleReplacementPlugin(), 
 new webpack.NoEmitOnErrorsPlugin() 
 ) 
 //sourcemap 
    config.devtool='#cheap-module-eval-source-map' 
} 
module.exports = config