【问题标题】:gulp + webpack + css-loader + typescript: "cannot find module"gulp + webpack + css-loader + typescript:“找不到模块”
【发布时间】:2016-01-20 07:33:55
【问题描述】:

我想在我的开发设置中使用 css-loader 和 :local() 函数。

没有错误:import './sidebar.css';

它编译没有问题,但是我不知道如何访问我的.tsx 文件中的本地类名。

错误: import classNames from './sidebar.css';

我在这里得到:error TS2307: Cannot find module './sidebar.css'

解释我的设置:

  1. .tsx 文件通过 gulp-typescript (ES5) 编译为 commonjs 模块
  2. commonjs 模块通过 webpack 编译并缩小为 JS

sidebar.tsx(如果重要,会在 app.tsx 中导入)

import classNames from './sidebar.css';

sidebar.css

.sl-sidebar {
  background-color: yellow;
}

gulpfile.js

Gulp 任务将 .tsx 文件编译为 commonJS 模块(当然在 webpack-task 之前运行):

gulp.task('gui-tsx', function () {
    return gulp.src(config.guiTsxPath + '**/*.tsx')
        .pipe(ts({
            jsx: 'react',
            outDir: config.guiCompiledPath,
            module: 'commonjs',
            target: 'ES5'
        }))
        .pipe(gulp.dest(config.guiCompiledPath));
});

我的 gulp-webpack 任务:

gulp.task('gui-webpack', function () {
    webpack({
        bail: false,
        debug: true,
        entry: './' + config.guiCompiledPath + 'app.js',
        output: {
            filename: "gui.js",
            path: './' + config.pubPath + 'js'
        },
        devtool: "#inline-source-map",
        plugins: [
            new webpack.optimize.UglifyJsPlugin({
                compress: {
                    warnings: false
                },
                output: {
                    comments: false,
                    semicolons: true
                },
                sourceMap: true
            })
        ],
        module: {
            loaders: [ {
                test: /\.css$/,
                loader: 'style-loader!css-loader?modules'
            }]
        }

    }, function (err, stats) {
        if (stats.compilation.errors.length > 0) {
            console.log(stats.compilation.errors[0].message);
        }
    });
});

我做错了什么?

编辑:我刚刚发现了这个:https://github.com/Microsoft/TypeScript/issues/2709 但我不太明白。这是否意味着我必须将我的 CSS 声明为模块?

【问题讨论】:

  • 你可以在 webpack 的帮助下转译 typescript,你不需要使用 gulp。查看文章了解更多详情:jbrantly.com/typescript-and-webpack
  • 我知道,但这并不能解决问题。与普通 webpack 相同

标签: css typescript gulp webpack webpack-style-loader


【解决方案1】:

要加载非 ts 资源,只需声明 require 函数并使用导入的资源(如 any)。

文档:https://github.com/TypeStrong/ts-loader#code-splitting-and-loading-other-resources

【讨论】:

【解决方案2】:

typescript 无法加载或理解 css 文件,但它可以与 webpack 一起使用。要告诉 TypeScript 有结尾不是 *.ts 的文件,您必须为相应的文件类型声明一个通配符模块。只需将其放入项目中包含的 *.d.ts 文件中即可。

// declaration.d.ts
declare module '*.css' {
    const content: any;
    export default content;
}

【讨论】:

    猜你喜欢
    • 2020-02-06
    • 2015-07-27
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    • 2019-05-17
    • 1970-01-01
    • 2020-04-25
    • 2021-09-13
    相关资源
    最近更新 更多