Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

webpack搭建vue项目 #46

Open
conan1992 opened this issue Jul 4, 2020 · 0 comments
Open

webpack搭建vue项目 #46

conan1992 opened this issue Jul 4, 2020 · 0 comments

Comments

@conan1992
Copy link
Owner

conan1992 commented Jul 4, 2020

考虑

首先明确我们的目的,然后执行;
那么搭建一个vue项目,我们就需要用到vue,webpack;
用到vue自然需要用到vue-loader(因为我们用.vue去编写组件);
当然用到的不止这些..但是这里暂时到这打住,后续在搭建过程中遇到问题,我们再逐一解决;(因为现在的我对整个过程不熟悉,不能考虑到所有需要用到的依赖,但是在后续过程中需要问题再解决,会加深自己的理解)

开始搭建

  • 初始化项目
mkdir vue_web_manny
cd vue_web_manny
npm init -y
  • 安装webpack vue vue-loader
$ npm install vue --save
npm WARN vue_web_manny@1.0.0 No description
npm WARN vue_web_manny@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.1.3 (node_modules\fse
vents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@
2.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"}
)
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\wa
tchpack-chokidar2\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@
1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"
})

+ vue@2.6.11
updated 1 package in 2.659s

$ npm install webpack vue-loader --save-dev
npm WARN vue-loader@15.9.3 requires a peer of css-loader@* but none is installed
. You must install peer dependencies yourself.
npm WARN vue_web_manny@1.0.0 No description
npm WARN vue_web_manny@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\wa
tchpack-chokidar2\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@
1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"
})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.1.3 (node_modules\fse
vents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@
2.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"}
)

+ webpack@4.43.0
+ vue-loader@15.9.3
added 365 packages from 208 contributors in 16.273s

安装完成npm给出警告:使用vue-loader时需要安装css-loader

这就是我最开始提到的,我们在搭建过程中遇到问题加深自己的印象,所以,我们继续安装css-loader

  • 安装css-loader
$ npm install css-loader --save-dev
npm WARN vue_web_manny@1.0.0 No description
npm WARN vue_web_manny@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.1.3 (node_modules\fse
vents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@
2.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"}
)
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\wa
tchpack-chokidar2\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@
1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"
})

+ css-loader@3.6.0
added 11 packages from 11 contributors in 4.653s
  • 到目前为止,项目搭建了个大概,让我们新建一个app.vue文件
+ src/app.vue
//app.vue
<template>
    <div>{{msg}}</div>
</template>
<script>
export default {
    data(){
        return {
            msg: "布加拉提"
        }
    }
}
</script>
<style scoped>
#text {
    color: red;
}
</style>

那么,怎么把这个app.vue文件解析成页面呢? app.vue文件就是我们安装的vue-loader来识别,webpack进行打包

webpack配置

  • 入口文件index.js
//index.js
import Vue from "vue"
import App from "./app.vue"

new Vue({
    render: h =>{
        return h(App)
    }
}).$mount("#app")
  • webpack配置文件
const path = require("path")

module.exports = {
    entry: path.join(__dirname, "src/index.js"),
    output: {
        filename: "bundle.js",
        path: path.join(__dirname, "dist")
    }
}
  • 打包
    首先在package.json配置
"scripts": {
    "build": "webpack --config webpack.config.js"
  },

打包

npm run build
$ npm run build

> vue_web_manny@1.0.0 build F:\study\vueProject\vue_web_manny
> webpack --config webpack.config.js

One CLI for webpack must be installed. These are recommended choices, delivered
as separate packages:
 - webpack-cli (https://github.com/webpack/webpack-cli)
   The original webpack full-featured CLI.
We will use "npm" to install the CLI via "npm install -D".
Do you want to install 'webpack-cli' (yes/no):

由于我使用的是webpack4,所以这里必须要安装一下cli,所以输入yes就会自动安装

$ npm run build

> vue_web_manny@1.0.0 build F:\study\vueProject\vue_web_manny
> webpack --config webpack.config.js

Hash: 49b0cb601c5c8552e443
Version: webpack 4.43.0
Time: 2209ms
Built at: 2020-07-04 2:31:30 PM
 1 asset
Entrypoint main = bundle.js
[0] (webpack)/buildin/global.js 472 bytes {0} [built]
[1] ./src/app.vue 282 bytes {0} [built] [failed] [1 error]
[3] ./src/index.js 131 bytes {0} [built]
    + 4 hidden modules

WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for th
is value. Set 'mode' option to 'development' or 'production' to enable defaults
for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https
://webpack.js.org/configuration/mode/

ERROR in ./src/app.vue 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loader
s are configured to process this file. See https://webpack.js.org/concepts#loade
rs
> <template>
|     <div>{{msg}}</div>
| </template>
 @ ./src/index.js 2:0-27 6:17-20
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! vue_web_manny@1.0.0 build: `webpack --config webpack.config.js`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the vue_web_manny@1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional log
ging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Administrator\AppData\Roaming\npm-cache\_logs\2020-07-04T0
6_31_30_709Z-debug.log

好家伙,又给我们报错了;从提示中可以看出,提示我们需要配置loader去识别vue文件

  • 加配置
const path = require("path")

module.exports = {
    entry: path.join(__dirname, "src/index.js"),
    output: {
        filename: "bundle.js",
        path: path.join(__dirname, "dist")
    },
    module: {
        rules: [{
            test: /.vue$/,
            loader: "vue-loader"
        }]
    }
}

继续npm run build看看

ERROR in ./src/app.vue
Module Error (from ./node_modules/vue-loader/lib/index.js):
[vue-loader] vue-template-compiler must be installed as a peer dependency, or a
compatible compiler implementation must be passed via options.
 @ ./src/index.js 2:0-27 6:17-20

ERROR in ./src/app.vue
Module Error (from ./node_modules/vue-loader/lib/index.js):
vue-loader was used without the corresponding plugin. Make sure to include VueLo
aderPlugin in your webpack config.
 @ ./src/index.js 2:0-27 6:17-20

继续报错:需要我们安装vue-template-compiler,并且在webpack.config.js添加插件VueLo
aderPlugin

  • 安装vue-template-compiler
npm install vue-template-compiler --save-dev
  • 添加插件
const path = require("path")
const VueLoaderPlugin = require("vue-loader/lib/plugin")
module.exports = {
    entry: path.join(__dirname, "src/index.js"),
    output: {
        filename: "bundle.js",
        path: path.join(__dirname, "dist")
    },
    plugins: [
        new VueLoaderPlugin()
    ],
    module: {
        rules: [{
            test: /.vue$/,
            loader: "vue-loader"
        }]
    }
}

继续打包

npm install build
...
ERROR in ./src/app.vue?vue&type=style&index=0&id=5ef48958&scoped=true&lang=css&
(./node_modules/vue-loader/lib??vue-loader-options!./src/app.vue?vue&type=style&
index=0&id=5ef48958&scoped=true&lang=css&) 14:0
Module parse failed: Unexpected character '#' (14:0)
File was processed with these loaders:
 * ./node_modules/vue-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
|
|
> #text {
|     color: red;
| }
 @ ./src/app.vue?vue&type=style&index=0&id=5ef48958&scoped=true&lang=css& 1:0-14
7 1:163-166 1:168-312 1:168-312
 @ ./src/app.vue
 @ ./src/index.js
...

我的天啊,又报错了,但是,这时候必须要稳住,不能急,我们继续看报错信息;原因是我们还未配置css-loader

  • 继续加配置
const path = require("path")
const VueLoaderPlugin = require("vue-loader/lib/plugin")
module.exports = {
    entry: path.join(__dirname, "src/index.js"),
    output: {
        filename: "bundle.js",
        path: path.join(__dirname, "dist")
    },
    plugins: [
        new VueLoaderPlugin()
    ],
    module: {
        rules: [{
            test: /.vue$/,
            loader: "vue-loader"
        },{
            test: /.css$/,
            use: ['style-loader',//接受潜在页面内部的style标签的文件。
            'css-loader']
        }]
    }
}

配置里面的style-loader是用来接收潜在页面内部的style标签,所以我们先安装

npm install style-loader
  • 好,再来打包一次
  npm run build

> vue_web_manny@1.0.0 build F:\study\vueProject\vue_web_manny
> webpack --config webpack.config.js

Hash: 6754ad2681859d4f0538
Version: webpack 4.43.0
Time: 2681ms
Built at: 2020-07-04 2:48:47 PM
    Asset      Size  Chunks             Chunk Names
bundle.js  73.6 KiB       0  [emitted]  main
Entrypoint main = bundle.js
 [0] ./node_modules/style-loader/dist/cjs.js!./node_modules/css-loader/dist/cjs.
js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/vue-l
oader/lib??vue-loader-options!./src/app.vue?vue&type=style&index=0&id=5ef48958&s
coped=true&lang=css& 692 bytes {0} [built]
 [1] (webpack)/buildin/global.js 472 bytes {0} [built]
 [3] ./src/app.vue?vue&type=style&index=0&id=5ef48958&scoped=true&lang=css& 588
bytes {0} [built]
 [5] ./node_modules/css-loader/dist/cjs.js!./node_modules/vue-loader/lib/loaders
/stylePostLoader.js!./node_modules/vue-loader/lib??vue-loader-options!./src/app.
vue?vue&type=style&index=0&id=5ef48958&scoped=true&lang=css& 284 bytes {0} [buil
t]
[10] ./src/index.js + 6 modules 4.79 KiB {0} [built]
     | ./src/index.js 131 bytes [built]
     | ./src/app.vue 1.16 KiB [built]
     | ./src/app.vue?vue&type=template&id=5ef48958&scoped=true& 207 bytes [built
]
     | ./src/app.vue?vue&type=script&lang=js& 248 bytes [built]
     | ./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-optio
ns!./node_modules/vue-loader/lib??vue-loader-options!./src/app.vue?vue&type=temp
late&id=5ef48958&scoped=true& 239 bytes [built]
     | ./node_modules/vue-loader/lib??vue-loader-options!./src/app.vue?vue&type=
script&lang=js& 114 bytes [built]
     |     + 1 hidden module
    + 6 hidden modules

WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for th
is value. Set 'mode' option to 'development' or 'production' to enable defaults
for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https
://webpack.js.org/configuration/mode/

皇天不负有心人,这次终于成功啦
image
可以kan看到,dist文件夹下多了一个bundle.js

思考

js文件是生成了,但是怎么在浏览器查看呢?

  • 这就需要用到webpack-dev-server
  • 安装并配置
//webpack.config.js添加
devServer: {
        contentBase: "./dist"
    }
//package.json添加
"scripts": {
    "dev": "webpack-dev-server --config webpack.config.js"
  }
  • 运行
  npm run dev

> vue_web_manny@1.0.0 dev F:\study\vueProject\vue_web_manny
> webpack-dev-server --config webpack.config.js

i 「wds」: Project is running at http://localhost:8081/
i 「wds」: webpack output is served from /
i 「wds」: Content not from webpack is served from ./dist
i 「wdm」: Hash: 8586d5c08e7163d00b5a
Version: webpack 4.43.0
Time: 1354ms

成功!是不是有点小开心~
打开浏览器一看
image

  • 完善:添加插件html-webpack-plugin
    安装后添加配置
plugins: [
        new VueLoaderPlugin(),
        new HtmlWebPlugin({
            title: "布加拉提",
        })
    ],

重新运行,查看页面,发现少了#app
image

  • 添加配置
plugins: [
        new VueLoaderPlugin(),
        new HtmlWebPlugin({
            title: "布加拉提",
            template: './public/index.html'
        })
    ],

当然,我们要在对应路径添加index.html;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=<device-width>, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app"></div>
</body>
</html>

template就是html-wepback-plugin用来当做模板的目标文件
好,继续运行试试;
image

参考

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant