9102年webpack4搭建vue项目的方法步骤

2020-06-13 10:40:56易采站长站整理

会打包生成一个新的dist文件夹

8.引入loader兼容代码


npm i babel-loader babel-core babel-preset-env -D

babel-preset-env 帮助我们配置 babel。我们只需要告诉它我们要兼容的情况(目标运行环境),它就会自动把代码转换为兼容对应环境的代码。

更改webpack.config.js文件


module: {
rules: [
{
test: '/.js$/',
include: path.resolve(__dirname + '/src'),
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: ['env'] }
] }
]}

9.下载vue并在main.js引入


import Vue from 'vue';
new Vue({
el: '#app',
data: {
msg: 'hello'
}
})

运行项目发现报错

vue.runtime.esm.js:620 [Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.

(found in <Root>)

报这个错误原因就是因为使用的是运行版本的vue,编译版本不能用,这时候在我们需要随后我们还要配置别名,将

resolve.alias
配置为如下对象


resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': path.resolve(__dirname, '/src')
}
}

然后在运行项目,发现已经在页面上打印出了hello。

一个简单的基于webpack的vue项目已经搭建好了。

接下来就是一些配置

10.配置css

输入命令下载style-loader css-loader


npm i style-loader css-loader -D

配置module中的rules


{
test: /.css$/,
use:['style-loader','css-loader'],
include: path.resolve(__dirname + '/src/'),
exclude: /node_modules/
}

测试引入css,新建index.css并在在main.js中引入

index.css


div{
color:skyblue;
}


import './index.css';

可以看到文字颜色已经改变了

11.支持图片

输入命令下载file-loader url-loader


npm i file-loader url-loader -D

配置module中的rules


{
test: /.(jpg|png|gif|svg)$/,
use: 'url-loader',
include: path.resolve(__dirname + '/src/'),
exclude: /node_modules/
}