找不到模块:错误:无法解析“ ./templates”

时间:2018-11-15 19:38:11

标签: javascript typescript webpack

我有这个javascript(TypeScript)文件

index.ts

import 
'../node_modules/bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap';
import * as templates from './templates';

document.body.innerHTML = templates.main;

const mainElement = 
document.body.querySelector('.b4.main');
const alertsElement = 
document.body.querySelector('.b4-alerts');

mainElement.innerHTML = templates.welcome;
alertsElement.innerHTML = templates.alert;

运行项目(使用webpack开发服务器)时,出现以下错误:

Module not found: Error: Can't resolve './templates' in '/Users/BorisGrunwald/Desktop/Node/b4-app/app'

我不明白为什么似乎找不到“ templates.ts”,因为两个文件都在同一个文件夹中。

这是我的项目结构的照片:

enter image description here

我的webpack配置:

'use strict';

const path = require('path');
const distDir = path.resolve(__dirname,'dist');

const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');

 module.exports = {
    entry: './app/index.ts',
    output: {
        filename: 'bundle.js',
        path: distDir
    },
    devServer: {
        contentBase:distDir,
        port:60800
    },
    plugins: [
        new HtmlWebpackPlugin({
            title: 'Better Book Bundle Builder'
        }),
        new webpack.ProvidePlugin({
            $:'jquery',
            jQuery:'jquery'
        })
    ],
    module: {
        rules: [{
            test:/\.ts$/,
            loader:'ts-loader'
        },{
            test: /\.css$/,
            use:['style-loader','css-loader']
        },{
            test: /\.(png|woff|woff2|eot|ttf|svg)$/,
            loader:'url-loader?limit=100000'
        }]
    }
};

Templates.ts

export const main = `
    <div class="container">
        <h1>B4 - Book Bundler</h1>
        <div class="b4-alerts"></div>
        <div class="b4-main"></div>
    </div>
`;

export const welcome = `
    <div class="jumbotron">
        <h1>Welcome!</h1>
        <p>B4 is an application for creating book bndles</p>
    </div>
`;

export const alert = `
    <div class="alert alert-success alert-dismissible fade in" 
role="alert">
        <button class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
        <strong>Success!</strong> Bootstrap is working
    </div>
`; 

谁能看到哪里出了问题?

1 个答案:

答案 0 :(得分:2)

尝试一下是否可行:

从'./templates'导入{主要,欢迎,警报};

Webpack默认情况下不查找.ts文件。您可以配置resolve.extensions查找.ts。别忘了也添加默认值,否则大多数模块都会中断,因为它们依赖于自动使用.js扩展名的事实。

resolve: {
    extensions: ['.ts', '.js', '.json']
}