如何使用Webpack 2 Raw-Loader读取文件

bri*_*her 2 node.js webpack raw-loader webpack-2 typescript2.0

我目前陷入困境,我需要在HTTPS模式下启动NodeJS服务器并需要读取cert文件,以便在https.createServer(options, app).listen(8443)命令中将它们作为选项.我很难掌握如何将文件读入使用Webpack 2捆绑的TypeScript文件中.例如,

我有2个文件file.crt和file.key.我想在创建https服务器并开始侦听给定端口时读取这些文件.在常规的TS/JS土地上,我可以这样做:

```

import Config from '../env/config';
import Express from '../lib/express';
import * as https from 'https';

import * as fs from 'fs';

let config = new Config();
let app = Express.bootstrap().app;

export default class AppService{

  constructor(){
    // console.log('blah:', fs.readFileSync('./file.txt'));
  }

  start(){

    let options = {
      key: fs.readFileSync('file.key'),
      cert: fs.readFileSync('file.crt'),
      ca: fs.readFileSync('ca.crt'),
      passphrase: 'gulp'
    };

    https.createServer(options, app).listen(config.port,()=>{
      console.log('listening on port::', config.port );
    });

  }
}
Run Code Online (Sandbox Code Playgroud)

但是,当webpack 2构建捆绑包时,这些文件不会被引入,因此当节点启动时它无法找到它们.好吧,我明白了,但我读到原始加载器会为此工作,所以我想我会尝试一下.

这是我的webpack配置文件:

// `CheckerPlugin` is optional. Use it if you want async error reporting.
// We need this plugin to detect a `--watch` mode. It may be removed later
// after https://github.com/webpack/webpack/issues/3460 will be resolved.
const {CheckerPlugin} = require('awesome-typescript-loader');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');

module.exports = {
  target: 'node',
  entry: './src/server.ts',
  output: {
    filename: 'dist/bundle.js'
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js', '.jsx']
  },
  
  devtool: 'source-map',
  
  module: {
    rules: [
      {test: /\.ts$/, use: 'awesome-typescript-loader'},
      {test: /\.json$/, loader: 'json-loader'},
      {test: /\.crt$/, use: 'raw-loader'}
    
    ]
  },
  plugins: [
    new CheckerPlugin()
  ],
  node: {
    global: true,
    crypto: 'empty',
    fs: 'empty',
    net: 'empty',
    process: true,
    module: false,
    clearImmediate: false,
    setImmediate: false
  }
};
Run Code Online (Sandbox Code Playgroud)

我认为,这意味着ok扫描项目,当你找到任何带有.crt的文件时,然后将它们与源地图捆绑为utf8字符串.我所要做的就是这import crtfile from 'file.crt'就像raw-loader doc状态一样,但是,typescript甚至无法编译文件现在声明它不能文件模块file.crt.请帮忙!!我撞墙了.

Mic*_*ngo 6

但是,当webpack 2构建捆绑包时,这些文件不会被引入,因此当节点启动时它无法找到它们.

Webpack仅捆绑您导入的文件.在您的情况下,您只是从文件系统中读取,而webpack不会触及这些功能.这并不意味着它在运行时不起作用,你只需要在你正在运行bundle的目录中找到你想要读取的文件,这些函数在bundle中没有不同的含义.

如果你想拥有包中文件的内容,你确实可以使用raw-loader.首先,import语句需要是相对路径,否则它会查找模块.

import crtfile from './file.crt';
Run Code Online (Sandbox Code Playgroud)

使用您的配置可以在JavaScript中正常工作.在TypeScript中,导入将是:

import * as crtfile from './file.crt';
Run Code Online (Sandbox Code Playgroud)

但TypeScript不满意导入类型未知的文件.例如,您可以通过在声明文件中定义类型来解决这个问题custom.d.ts(如导入非代码资产中所示).

declare module "*.crt" {
  const content: any;
  export default content;
}
Run Code Online (Sandbox Code Playgroud)