在 Laravel 中使用 TypeScript 、CoffeeScript 、pug 提高開發效率

家豬配種專家發表於2019-12-13

需要的 npm

// package.json
"devDependencies": {
   ...
    "coffee-loader": "^0.9.0",
    "coffeescript": "^2.4.1",
    "pug": "^2.0.4",
    "pug-cli": "^1.0.0-alpha6",
    "pug-filters": "^3.1.1",
    "pug-loader": "^2.4.0",
    "resolve-url-loader": "^2.3.1",
    "sass": "^1.15.2",
    "sass-loader": "^7.3.1",
    "typescript": "^3.7.3"
},
"dependencies": {
    ...
    "pug-plain-loader": "^1.0.0",
    "ts-loader": "^6.2.1",
    "vue": "^2.6.10",
    "vue-lazyload": "^1.3.3",
    "vue-router": "^3.1.3"
}

配置 webpack.mix.js
(僅在 vue 單檔案中使用 CoffeeScript,在其餘指令碼檔案中使用 TypeScript)

mix.webpackConfig({
    module: {
        rules: [
            {
                test: /\.pug$/,
                oneOf: [
                    {
                        resourceQuery: /^\?vue/,
                        use: ['pug-plain-loader']
                    }
                ]
            },
            {
                test: /\.scss$/,
                oneOf: [
                    {
                        resourceQuery: /^\?vue/,
                        use: ['sass-loader']
                    }
                ]
            },
            {
                test: /\.coffee$/,
                oneOf: [
                    {
                        resourceQuery: /^\?vue/,
                        use: ['coffee-loader']
                    }
                ]
            },
            {
                test: /\.ts?$/,
                loader: 'ts-loader',
                exclude: /node_modules|vue\/src/,
                options: {
                    appendTsSuffixTo: [/\.vue$/]
                },
                exclude: /node_modules/,
            },
        ]
    },
    resolve: {
        extensions: ['*', '.js', '.jsx', '.vue', '.ts', '.tsx','.coffee'],
    },
});

mix.ts('resources/js/app.ts', 'public/js')
    .sass('resources/sass/app.scss', 'public/css')
    .version();

新增 tsconfig.json 至專案根

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": false,
        "sourceMap": true
    }
}

現在你可以在 vue 單檔案中這樣寫了

<template lang="pug">
    .container {{ text }}
</template>
<style lang="scss">
    .container{
        &:hover{
            border:1px solid #fff;
        }
    }
</style>
<script lang="coffee">
export default
    data: -> 
        text:'my text'
</script>

GitHub :laravel-efficient-front-end

相關文章