webpack搭建基础vue项目

2022-09-08 16:38:24 浏览数 (1)

新键目录

  • 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

代码语言:javascript复制
<template> 
 <div id="app"> 
      hello word  
 </div> 
</template> 
<script> 
export default { 
    data(){ 
 return { 
          title:'word hello' 
 } 
 } 
} 
</script> 
<style> 
</style> 

index.js

代码语言:javascript复制
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

代码语言:javascript复制
... 
"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

代码语言:javascript复制
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 

0 人点赞