webpack4 + vue + typescript搭建
2019-10-10 本文已影响0人
wo_稀饭
最近看vue ,vue 官方出 vue-cli 可以快速搭建。但是我还是想自己搭建试试
npm init
一路回车,生成package.json文件
安装必要的文件。我装的比较多,项目中还有其他的配置
"dependencies": {
"core-js": "^2.6.5",
"file-loader": "^4.2.0",
"vue-class-component": "^7.0.2",
"vue-property-decorator": "^8.1.0",
"vue-router": "^3.0.3",
"vuex": "^3.0.1"
},
"devDependencies": {
"@babel/plugin-transform-modules-commonjs": "^7.6.0",
"@babel/plugin-transform-runtime": "^7.6.2",
"@types/jest": "^23.1.4",
"babel-core": "7.0.0-bridge.0",
"babel-eslint": "^10.0.1",
"copy-webpack-plugin": "^5.0.4",
"cross-env": "^6.0.3",
"css-loader": "^3.2.0",
"eslint": "^5.16.0",
"eslint-plugin-prettier": "^3.1.0",
"eslint-plugin-vue": "^5.0.0",
"friendly-errors-webpack-plugin": "^1.7.0",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.8.0",
"node-sass": "^4.9.0",
"optimize-css-assets-webpack-plugin": "^5.0.3",
"prettier": "^1.18.2",
"sass-loader": "^7.1.0",
"scss-loader": "0.0.1",
"style-loader": "^1.0.0",
"ts-loader": "^6.2.0",
"typescript": "^3.4.3",
"vue": "^2.6.10",
"vue-loader": "^15.7.1",
"vue-style-loader": "^4.1.2",
"vue-template-compiler": "^2.6.10",
"vue-test-loader": "^0.4.1",
"webpack": "^4.41.0",
"webpack-cli": "^3.3.9",
"webpack-dev-server": "^3.8.2",
"webpack-merge": "^4.2.2"
}
需要安装的插件我们已经安装完毕,不要忘了设置启动项
"scripts": {
"dev": "webpack-dev-server --open --config ./build/webpack.config.js",
"build": "webpack",
"test": "echo \"Error: no test specified\" && exit 1"
},
在项目文件下新建build文件,新建webpack.config.js,开始配置 webpack。直接方代码
const path = require('path');
const HtmlWebpackPlugin=require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
module.exports={
// model:'development',
entry:'./src/main.ts',
output:{
filename:'bundle.js',
path: path.resolve(__dirname,'../dist/index.html')
},
module:{
rules:[
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
compilerOptions: {
preserveWhitespace: false
}
}
},
{
test:/\.tsx?$/,
loader:'ts-loader',
exclude:/node_modules/,
options: {
appendTsSuffixTo: [/\.vue$/]
}
},
{
test: /\.(sa|sc|c)ss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader'
],
exclude: /node_modules/
},
]
},
resolve:{
//引入模块的时候可以少写后缀
extensions:['.js', '.vue', '.json', '.ts', '.tsx'],
alias: {
vue$: 'vue/dist/vue.esm.js',
}
},
devtool: 'inline-source-map',
devServer:{
contentBase:path.join(__dirname, "dist"),
},
plugins:[
new VueLoaderPlugin(),
new MiniCssExtractPlugin({
// 类似 webpackOptions.output里面的配置 可以忽略
filename: '[name].css',
chunkFilename: '[id].css',
}),
new HtmlWebpackPlugin({
title:'typescript学习',
template: './public/index.html',
inject:true
})
]
}
新建src 文件夹。在文件夹下新增 vue-shim.d.ts 。需要新增这个文件,因为js本身是没有类型的,ts的语言服务需要.d.ts文件来识别类型,这样才能做到相应的语法检查和智能提示,我们自己编写的.d.ts文件直接放在项目的目录下,ts自己会去识别,
declare module "*.vue" {
import Vue from "vue";
export default Vue;
}
项目结构
image.png