webpack搭建vue 项目的步骤(2)

babel的使用请阅读官网文档http://babeljs.cn/。

将babel加入到webpack.config.js 配置文件中:

const path = require('path')

module.exports ={
 entry:'./src/main.js',
 output:{
  path:path.resolve(__dirname,'dist'),
  filename:"demo.js"
 },
 module:{
  rules:[
   {
    test: /\.js$/,
    loader:"babel-loader",
    exclude: /node_modules/
   }
  ]
 }
}

然后命令行输入 webpack 命令即可进行编译,再编译完成后用浏览器打开index.html 文件,此时会发现浏览器控制台出现以下错误:

[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: {
  'vue$': 'vue/dist/vue.esm.js' // 'vue/dist/vue.common.js' for webpack 1
 }
 }

此时在运行webpack 命令重新编译,编译后在访问index.html页面,页面内容如下图

此时一个基于webpack的vue 项目就搭建好。

webpack的一些常用配置

在项目的实际开发中我们还会引入css、图片以及字体等资源文件。这些文件的引入都需要相应的加载器才能将其加载到项目中并正常使用。

下面只介绍部分我们需要的加载器的使用方法, 更多信息请查阅webpack加载器文档。

css加载器

我们需要引入css-loader、和style-loader (安装style-loader的目的是为了在html中以style的方式嵌入css )。

执行命令

npm install --save-dev css-loader style-loader

在 webpack.config.js 中进行如下配置

module: {
  rules: [{
   test: /\.js$/,
   loader: "babel-loader",
   exclude: /node_modules/
  }, {
   test: /\.css$/,
   loader: 'style-loader!css-loader'
  }]
 },

然后再src 目录下 新建一个styles的文件夹并在里面添加一个main.css的文件,写上以下内容

#app{
 color:red;
}

然后再运行 webpack 命令, 并重新加载index.html 文件 ,可见css已经生效,效果如下图

 

图片资源的加载

使用file-loader或者url-loader加载器进行加载,他们都是用于打包文件和图片资源的,两者的区别是url-loader在file-loader的基础上进行了一次封装。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/468.html